Rails:在has-many / belongs-to关联中查找匹配属性

时间:2015-07-24 11:54:20

标签: ruby-on-rails

说我有RestaurantReservation型号。我想根据餐馆ID找到每家餐厅的预订,如下所示:

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

尝试此操作时,这会构造一个数组,我试图将其转换为Active Record对象,但是不成功。我错过了什么,还是有更明显的方法来做到这一点?

2 个答案:

答案 0 :(得分:1)

restaurant.rb

has_many :reservations

预订

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

您可以找到此预订的餐馆记录

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

答案 1 :(得分:0)

#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

编辑 - 添加了flatten,在评论中添加了解释