Reputation: 10683
I currently use two queries to solve my problem and I'm sure it's possible to merge them into one. I currently have:
guest = Guest.find_by(email: params[:email].downcase)
booking = Booking.find_by(guest_id: guest.id)
The Guest and Booking models are related - One Guest has many Bookings.
I think I saw on the Rails guides somewhere how to do this with just one query but I cannot find the page.
Upvotes: 0
Views: 72
Reputation: 29291
Since you have your model associations in place, the answer is far simpler than you think:
bookings = Guest.find_by_email(params[:email].downcase).bookings
No need for joins in this case.
Upvotes: 1
Reputation: 3112
There are several ways. The main object is not to write less lines, but to have readable code.
I'd do it this way bro:
# For style and readability, put this in a separate line:
email = params[:email].downcase
# then:
bookings = Guest.find_by( email: email ).bookings
Make sure you've declared that the Guest
class has_many :bookings
.
Upvotes: 1
Reputation: 2322
If i'm not mistaken you could try
Booking.joins(:guest).where(guests: {email: params[:email].downcase}).all
Check out also http://guides.rubyonrails.org/active_record_querying.html for more info.
Upvotes: 0