我正在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每一次投票都有一个用户和一个报告。
在我看来,我需要以下几点,希望尽可能容易:
现在,我对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 %>Helper
def hasVoted(current_user_id, report_id)
if(Vote.exists?(:user_id => current_user_id, :report_id => report_id))
true
else
false
end
end希望这能让你对helping...thanks有一些了解!
发布于 2012-07-31 06:04:50
好的。
首先,请考虑命名您的方法has_voted?而不是hasVoted。其次,考虑在用户模型中移动该方法。
#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的新手,所以我不会在控制器中将报表查询复杂化,在控制器中获取报告以包含选票计数(除非您要求我这样做)。但是,一旦你对这里发生的事情感到满意,那就是你要优化的地方。
https://stackoverflow.com/questions/11733976
复制相似问题