通过检查多对多表中是否存在多个条目来过滤对象

时间:2019-04-05 04:08:51

标签: ruby-on-rails activerecord

我有三个表:listingsamenitieslisting_amenities。我有一个过滤器,用户可以按设施过滤列表,在我的控制器中,我将其过滤器作为amenity描述的数组。我正在尝试筛选包含所有amenities的列表。目前,我可以过滤,但只能成功检查listings是否至少具有所提供的amenities中的一个。

当前查询:

  scope :filter_by_amenities, ->(amenities) { # amenities is array of descriptions
    includes(:listing_amenities)
      .where(listing_amenities: {
               :amenity_id => (
                 Amenity.where(:description => amenities)
               )
             })
  }

如何修改查询以仅返回具有所有便利设施的列表,而不返回至少一项?

1 个答案:

答案 0 :(得分:0)

这可以通过使用类方法并迭代查询结果记录来完成。

  def self.filter_by_amenities(amenities)
    amenity_ids = Amenity.where(:description => amenities).pluck(:id)
    records = self.all
    amenity_ids.each do |amenity_id|
      record_ids = records.includes(:listing_amenities).where(listing_amenities: {:amenity_id => amenity_id)}).pluck(:id)
      records = records.where(id: record_ids)
    end  
    records
  end