Show data from 2 models in 1 view

I have 2 models: AvailableDates → belongs_from: spec and Spec → has_many: available_dates Now I have a view where I want to display data from both Spec and AvailableDates with 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 as follows: 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 does not seem like "rails like", so I want to do it this way, 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? Thank!

Update: I now have this:

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

But it only gives me data from Friend. How can I get data from the corresponding data_data and specifications?

+3
source share
2 answers

, joins include ActiveRecord find. API find Railscasts, .

+5

, : include, :

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

Source: https://habr.com/ru/post/1776640/


All Articles