2010-11-24 50 views
3

我有2个模型:AvailableDates - > belongs_to:spec和Spec - > has_many:available_dates 现在我有一个视图,我想要显示来自Spec和AvailableDates的数据,相同的friend_id属性。从两个模型在1视图中显示来自2个模型的数据

@invitees = AvailableDate.find_by_sql "SELECT d.friend_id, s.first_name, s.last_name, s.gender, s.birthdate, s.occupation, s.country, s.city FROM available_dates d, specs s WHERE d.friend_id = s.friend_id AND d.city = 'London' 

的观点看起来是这样,随着数据:我可以用SQL,它工作得很好做到这一点

<% @invitees.each do |invitee| %> 
     <tr> 
     <td><%=h invitee.first_name %></td> 
     <td><%=h invitee.last_name %></td> 
     <td><%=h invitee.gender %></td> 
     <td><%=h invitee.birthdate %></td> 
     </tr> 
    <% end %> 

然而,这并不觉得“像轨道”,所以我想这样做,这样一来,同时保持在观点不变代码:

@invitees = AvailableDate.find(:all, :conditions => ["country = ? and city = ? and start_date <= ? and end_date >= ?", country, city, date, date]) 

    # Retrieve spec data for every matching invitee 
    @invitees.each do |invitee| 
     @spec = Spec.find(:first, :conditions => ["friend_id = ?", invitee.friend_id]) 
    end 

有没有人有一个更好的解决方案?谢谢!

更新:我现在有这其中的工作原理:

@invitees = Friend.find(:all, :include => [:available_date, :spec], :conditions => ["specs.country = ?", "United Kingdom"]) 

但它只是给我的数据来自朋友。我怎样才能从关联的available_date和spec中获取数据?

回答

5

您可能想要使用joinsinclude参数来ActiveRecord的find方法。看看API documentationfindRailscasts episode,它解释了两者之间的差异。

+0

感谢,我研究了:包括和:条件,想我明白了。将回来与我的解决方案。 – John 2010-11-24 20:37:54

0

你做了之后:包括您可以访问相关的数据是这样的:

@invitees.each do |invite| 
    invite.available_date.city 
    invite.spec.first_name 
end 
+0

谢谢,确实有效! – John 2010-11-25 08:19:47

相关问题