Ruby on Rails query not working properly

孤街醉人 提交于 2020-01-16 04:09:07

问题


I have several listings, and I define a number of filters. In particular, a listing has_many :spaces, through: :designations and has_many :amenities, through: :offerings.

I use the filters to restrict the listings that get shown.

The two main ones are:

# filter by space type
if params[:search][:space_ids].present? && params[:search][:space_ids].reject(&:blank?).size > 0
  @listings = @listings.joins(:spaces).where('space_id IN (?)', params[:search][:space_ids].reject(&:blank?)).uniq
end

# filter by amenities
if params[:search][:amenity_ids].present? && params[:search][:amenity_ids].reject(&:blank?).size > 0
  @listings = @listings.joins(:amenities).where(amenities: { id: params[:search][:amenity_ids].reject(&:blank?) }).group('listings.id').having('count(*) = ?', params[:search][:amenity_ids].reject(&:blank?).size)
end

The first filter says: get all of the listings that match ANY of the selected space types.

The second filter says: get all of the listings that have ALL of the selected amenities.

These filters work for the most part, but not always. In particular, suppose that listing A has space types 1 and 2 and amenity 2. If I filter for space types 1 and 2 (so space_ids: ['1', '2', '']) and amenity 2 (so amenity_ids: ['2', '']), I get: #<ActiveRecord::Relation []>.

But I should get listing A. What is wrong with the query?

Basically, I am trying to implement this: Complex Rails query using ActiveRecord on Many to Many relationship

Or this: http://blog.hasmanythrough.com/2006/6/12/when-associations-arent-enough-part-2


回答1:


Changing having('count(*) = ?', params[:search][:amenity_ids].reject(&:blank?).size) to having('count(*) >= ?', params[:search][:amenity_ids].reject(&:blank?).size) (i.e., = to >=) fixes the issue.

But now there is another issue: Ruby on Rails query yielding unexpected results.



来源:https://stackoverflow.com/questions/33447254/ruby-on-rails-query-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!