我有2个模型:AvailableDates - > belongs_to:spec和Spec - > has_many:available_dates现在我有一个视图,我想要显示来自Spec和AvailableDates的数据,并且具有相同的friend_id属性.我可以用SQL做到这一点,它工作正常:
@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'
Run Code Online (Sandbox Code Playgroud)
视图将如下所示,包含两个模型的数据:
<% @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 %>
Run Code Online (Sandbox Code Playgroud)
但是,这并不觉得"像铁轨一样",所以我想这样做,同时保持视图中的代码不变:
@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
Run Code Online (Sandbox Code Playgroud)
有没有人有更好的解决方案?谢谢!
更新:我现在有这个工作:
@invitees = Friend.find(:all, :include => [:available_date, :spec], :conditions => ["specs.country = ?", "United Kingdom"])
Run Code Online (Sandbox Code Playgroud)
但它只给了我朋友的数据.我如何从关联的available_date和spec获取数据?
| 归档时间: |
|
| 查看次数: |
1110 次 |
| 最近记录: |