使用has_many:through关系连接获取记录

时间:2016-03-31 07:03:09

标签: ruby-on-rails ruby

我有一个Hotel模型和HotelAmenity模型以及Amenity模型,它们与has_many :through相关联:

class Hotel < ActiveRecord::Base
    has_many :hotel_amenities, :dependent => :destroy
    has_many :amenities, through: :hotel_amenities
end

class Amenity < ActiveRecord::Base
    has_many :hotel_amenities, :dependent => :destroy
    has_many :hotels, through: :hotel_amenities
end


class HotelAmenity < ActiveRecord::Base
  belongs_to :amenity
  belongs_to :hotel
end

现在我的行​​动中有hotel_id,我想要抓取所有有设施的酒店[1,2,3]这是array的{​​{1}}。

2 个答案:

答案 0 :(得分:2)

好问题!! 不用担心,您可以使用join上的Hotel Model解决此问题: 首先,您可以通过hotel_id

找到酒店
@hotel= Hotel.find_by_id(params[:user_id))

现在,您可以找到amenity_array [1,2,3]

的酒店
 @hotels = @hotels.joins(:hotel_amenities).where(hotel_amenities: { amenity_id: [1,2,3] }) // this can returns a hotel two or more time


@hotels = @hotels.joins(:hotel_amenities).where(hotel_amenities: { amenity_id: [1,2,3] }).uniq // this will return all hotels without redundant records 

希望这对你有用。

答案 1 :(得分:0)

试试这段代码:

arr= [1,2,3] 
Hotel.joins(:hotel_amenities).select("hotel_amenities.*,hotels.*").where("hotel_amenities.amenity_id= ?",arr)