2012-07-31 66 views
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 

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

在我看来,我必须满足下列条件,希望尽可能方便:

  1. 投票从所有用户的每个报告总数
  2. 真/假,如果用户已经投票的具体报告

现在,我的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 

希望能给你一些见解,帮助...谢谢!

回答

1

当然。

首先,请考虑命名您的方法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的新手,我不会在控制器中将您的报告查询复杂化,您可以在其中获取报告以包含投票计数(除非您要求我提供)。但是,一旦你对这里发生的事情感到满意,那就是你要优化的地方。

+0

谢谢,那么我需要在查询中添加一个'include'子句吗?或者ActiveRecord会根据'Reports'模型建立关联关系? – 2012-07-31 06:08:11

+0

您不需要在查询中包含投票。如果我们正在编写一个更复杂的查询,那么一次性获取报告信息和投票计数,我们将包括投票。 – 2012-07-31 06:11:07

+0

我做了一个'<%= debug report%>',看起来我在设置表格时没有正确地建立关联关系,我在'Vote'表格中手动添加了一个'report_id'列,一旦我正确地建立连接,我认为你的ActiveRecord应该足够聪明,只需通过查询“Report” – 2012-07-31 06:15:42