gpt4 book ai didi

ruby-on-rails - 使用 join with has_many :through relationship 获取记录

转载 作者:数据小太阳 更新时间:2023-10-29 09:00:42 27 4
gpt4 key购买 nike

我有一个 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] 这是 arrayamenity_id

最佳答案

好问题!!别担心,您可以使用 Hotel Model 上的 join 来解决这个问题:首先,您将通过 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

希望这对你有用。

关于ruby-on-rails - 使用 join with has_many :through relationship 获取记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36326338/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com