Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Activerecord关系联接_Ruby On Rails_Activerecord - Fatal编程技术网

Ruby on rails Activerecord关系联接

Ruby on rails Activerecord关系联接,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我正在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 查看 <% @r

我正在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
查看

<% @reports.each do |report| %>
    <% if(hasVoted(@current_user.id, report.id)) %>
        <!-- display the 'has voted html' -->
    <% end %>
<% end %>
希望能给你一些帮助…谢谢

当然

首先,请考虑命名你的方法是否被投票了?而不是投票。其次,考虑在用户模型中移动该方法。
#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 %>


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

谢谢,那么我是否需要在查询中添加一个
include
子句?或者ActiveRecord会仅仅根据
报告
模型进行关联吗?您还不需要在查询中包含投票。如果我们正在编写一个更复杂的查询,它将一次性获取报告信息和投票计数,那么我们将包含投票。我做了一个
,看起来我在设置表时没有正确地进行关联,我做的有点像是在
投票表中手动添加一个
报告id
列,一旦我建立了正确的连接,我认为您的右ActiveRecord应该足够智能,只需查询
报告
即可返回相关的
投票
记录。您的意思是因为您没有\@Report instance变量,只有\@reports(复数版本)。啊..很抱歉,我假设您是rails新手,有时我在回答另一个问题时会想起最近的一个问题。
<% if current_user.voted_on?(report) %>
  ...
<% end %>
<% vote_count = report.votes.size %>