0

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?

2 Answers 2

2

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 %>
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic - and went to extra length to show me example. Cheers for the help
1

In your bookings controller:

@bookings = Booking.includes(:guest).all

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.