【发布时间】: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
每个投票都有一个用户和一个报告。
在我看来,我需要以下内容,希望尽可能简单:
- 所有用户对每个报告的总投票数
- 如果用户对特定报告进行了投票,则为真/假
目前,我对 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