说我有Restaurant
和Reservation
型号。我想根据餐馆ID找到每家餐厅的预订,如下所示:
@reservations = Reservation.find( # current user )
@restaurants = []
@reservations.each do |res|
@restaurants += Restaurant.where('id like ?', res.rest_id)
end
尝试此操作时,这会构造一个数组,我试图将其转换为Active Record对象,但是不成功。我错过了什么,还是有更明显的方法来做到这一点?
答案 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
,在评论中添加了解释