user516541
user516541

Reputation:

Rails: Finding matching attribute in a has-many / belongs-to association

Say I have a Restaurant and a Reservation model. I want to find the reservations for each restaurant according to restaurant id, something like this:

@reservations = Reservation.find( # current user )
@restaurants = []
@reservations.each do |res|
  @restaurants += Restaurant.where('id like ?', res.rest_id)
end

When trying this, this constructs an array, which I've tried to convert to an Active Record object un-successfully. Am I missing something, or is there a more obvious way to do this ?

Upvotes: 0

Views: 32

Answers (2)

Max Williams
Max Williams

Reputation: 32943

#load all reservations matching your condition, and eager-load all associated restaurants
@reservations = Reservation.where(<some condition>).includes(:restaurants)

#get all associated restaurants for all objects in the @reservations collection 
#which have been eager loaded, so this won't hit the db again), 
#flatten them to a single array, 
#then call `uniq` on this array to get rid of duplicates
@restaurants = @reservations.map(&:restaurants).flatten.uniq

EDIT - added flatten, added explanation in comments

Upvotes: 0

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

restaurant.rb

has_many :reservations

reservation

belongs_to :restaurant, class_name: 'Restaurant', foreign_key: 'rest_id'

You can find restaurant record for this reservation as

@reservation = Reservation.joins(:restaurant).where(id: reservation_id)

Upvotes: 1

Related Questions