0
我在Rails和ActiveRecord的工作,并试图合并在一起,在我看来,从相关表的一些数据,这里是我的模型: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
创建帮手和查询比对existe的report
同样NCE进入点票总数为所有用户提供一个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
希望能给你一些见解,帮助...谢谢!
谢谢,那么我需要在查询中添加一个'include'子句吗?或者ActiveRecord会根据'Reports'模型建立关联关系? – 2012-07-31 06:08:11
您不需要在查询中包含投票。如果我们正在编写一个更复杂的查询,那么一次性获取报告信息和投票计数,我们将包括投票。 – 2012-07-31 06:11:07
我做了一个'<%= debug report%>',看起来我在设置表格时没有正确地建立关联关系,我在'Vote'表格中手动添加了一个'report_id'列,一旦我正确地建立连接,我认为你的ActiveRecord应该足够聪明,只需通过查询“Report” – 2012-07-31 06:15:42