Active Record查询通过关系查找与Rails has_many中的所有条件匹配的记录

时间:2016-10-28 16:01:20

标签: sql ruby-on-rails postgresql activerecord

我有两个型号,公寓和设施,通过ApartmentAmenities关联。我正在尝试实施一个过滤器,我只显示具有所有指定设施的公寓。

class Amenity < ActiveRecord::Base  
  has_many :apartment_amenities
  has_many :apartments, through: :apartment_amenities
end

class ApartmentAmenity < ActiveRecord::Base
  belongs_to :apartment
  belongs_to :amenity
end

class Apartment < ActiveRecord::Base
  has_many :apartment_amenities
  has_many :amenities, through: :apartment_amenities
end

我有一个查询工作,将返回所有与给定集合中的至少一个设施匹配的公寓,如下所示:

Apartment.joins(:apartment_amenities).where('apartment_amenities.amenity_id IN (?)', [1,2,3])

但这并不是我想要的。

1 个答案:

答案 0 :(得分:2)

好吧,在放弃了几天然后回到它之后,我终于找到了这个问题:How to find records, whose has_many through objects include all objects of some list?

这使我得到了正确的答案:

  def self.with_amenities(amenity_ids)
    where("NOT EXISTS (SELECT * FROM amenities
      WHERE NOT EXISTS (SELECT * FROM apartment_amenities
        WHERE apartment_amenities.amenity_id = amenities.id
        AND apartment_amenities.apartment_id = apartments.id)
      AND amenities.id IN (?))", amenity_ids)
  end