我有三个表:listings
,amenities
和listing_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)
)
})
}
如何修改查询以仅返回具有所有便利设施的列表,而不返回至少一项?
答案 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