Reputation: 10703
I have read so much about Rails in the past week in the process of trying to learn it. The problem is when I need something I find it difficult to recall where I read it! ha ha
I have two models: Guest and Booking where Guests has_many Bookings. Therefore the Booking model has a guest_id field included.
I would like to retrieve all the booking data and the guest data and display in a view as one object. I know I have seen a simple solution to this (in the Rails doc I think) that does just this.
At the moment I'm doing the following in my BookingsController:
@bookings = Booking.all
and in my associated view I have:
<% @bookings.each do |booking| %>
<p><%= booking.id %></p>
<p><%= booking.email %></p> //this does not work as email is in guests table!!!
<% end %>
but how can I get the linked Guest table included too?
Upvotes: 0
Views: 2457
Reputation: 7160
If your booking belongs to guest
class Booking < ActiveRecord::Base
belongs_to :guest
...
end
you can first include guest to avoid n+1 queries
@bookings = Booking.includes(:guest).all
and then in view, traverse the association
<% @bookings.each do |booking| %>
<p><%= booking.id %></p>
<p><%= booking.guest.email %></p>
<% end %>
Upvotes: 2
Reputation: 1449
In your bookings controller:
@bookings = Booking.includes(:guest).all
Upvotes: 1