【问题标题】:Activerecord relationship joinsActiverecord 关系连接
【发布时间】:2012-07-31 14:04:50
【问题描述】:

我正在使用 Rails 和 Activerecord 并尝试在我的视图中将相关表中的一些数据合并在一起,这是我的模型:

class Report < ActiveRecord::Base
  has_many :votes
end

class Vote < ActiveRecord::Base
  belongs_to :reports
end

class User < ActiveRecord::Base
  has_many :votes
end

每个投票都有一个用户和一个报告。

在我看来,我需要以下内容,希望尽可能简单:

  1. 所有用户对每个报告的总投票数
  2. 如果用户对特定报告进行了投票,则为真/假

目前,我对 ActiveRecord 查询的基本了解只需要我用报告和当前的user 创建一个帮助器,而不是查询report 的存在

计算所有用户对report 的总票数也是如此:

控制器

def index
  #this is where I need some help to get the related information into a single
  #object
  @reports = Report.where('...')
end

查看

<% @reports.each do |report| %>
    <% if(hasVoted(@current_user.id, report.id)) %>
        <!-- display the 'has voted html' -->
    <% end %>
<% end %>

助手

def hasVoted(current_user_id, report_id)
    if(Vote.exists?(:user_id => current_user_id, :report_id => report_id))
      true
    else
      false
    end      
end

希望这能让您对帮助有所了解...谢谢!

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    当然。

    首先,请考虑将您的方法命名为 has_voted?而不是已投票。其次,考虑在用户模型中移动该方法。

    #user.rb
    def voted_on?(report_id)
      votes.where(:report_id => report_id).exists?
    end
    

    然后您的视图将读取

    <% if current_user.voted_on?(report) %>
      ...
    <% end %>
    

    您遇到的另一个问题是找出报告获得的票数。这也很简单。您可以在循环内的视图中执行此操作,在该循环中迭代 @reports

    <% vote_count = report.votes.size %>
    

    请记住,他会产生 N 个查询(其中 N = 报告数)。由于您是 Rails 新手,我不会在控制器中使您的 Reports 查询复杂化,您可以在控制器中获取报告以包括投票计数(除非您要求我这样做)。但是,一旦您对这里发生的事情感到满意,那就是您要优化的地方。

    【讨论】:

    • 谢谢,我需要在查询中添加include 子句吗?还是 ActiveRecord 只是根据Reports 模型进行关联?
    • 您现在不需要在查询中包含投票。如果我们正在编写一个更复杂的查询,该查询将一次性获取报告信息和投票计数,我们将包括投票。
    • 我做了一个&lt;%= debug report %&gt;,看起来我在设置表格时没有正确建立关联,我手动将report_id 列添加到Vote 表格,一旦我正确地建立连接,我认为你的正确 ActiveRecord 应该足够聪明,只需通过查询 Report 来返回相关的 Votes 记录
    • 你的意思是 因为你没有 \@report 实例变量,只有 \@reports(复数版本)。
    • 呃..我很抱歉假设您是 Rails 新手,有时我在回答另一个问题时会想到最近的一个问题。
    猜你喜欢
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多