我有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中獲取數據?
感謝,我研究了:包括和:條件,想我明白了。將回來與我的解決方案。 – John 2010-11-24 20:37:54