我有一个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}}。
答案 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)