Show data from 2 models in 1 view
I have 2 models: AvailableDates --> belongs_to :spec and Spec --> has_many :available_dates Now I have a view where I want to show data from both Spec and AvailableDates whith the same friend_id attribute. I can do this with SQL, which works fine:
@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'
The view will look like this, with data from both models:
<% @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 %>
However, this doesn't feel "rails like", so I want to do it this way, while keeping the code in the view unchanged:
@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
Does anyone have a better solution? Thanks!
Update: I now have th开发者_JAVA技巧is which works:
@invitees = Friend.find(:all, :include => [:available_date, :spec], :conditions => ["specs.country = ?", "United Kingdom"])
But it only gives me data from Friend. How do I also get data from the associated available_date and spec?
You probably want to use the joins
or include
parameters to ActiveRecord's find
method. Take a look at the API documentation for find
and the Railscasts episode that explains the difference between the two.
After you have done the :include you can access the associated data like this:
@invitees.each do |invite|
invite.available_date.city
invite.spec.first_name
end
精彩评论