Ruby on Rails的查询不工作正常 [英] Ruby on Rails query not working properly

查看:161
本文介绍了Ruby on Rails的查询不工作正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个列表和本人限定数量的过滤器。特别是,上市的has_many:空间,通过:名称的has_many:设施,通过::产品

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.

这两个主要的有:

# 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.

这些滤波器在大多数情况下工作,但并非总是如此。具体而言,假设上市A有空间,1型和2和市容2.如果我筛选的空间1型和2(SO space_ids:['1','2',''] )和市容2(SO amenity_ids:['2',''] ),我得到:#< ActiveRecord的: :关系[]>

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 []>.

不过,我应该得到上市A.什么是错的查询?

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

基本上,我想实现这一点:<一href="http://stackoverflow.com/questions/30812122/complex-rails-query-using-activerecord-on-many-to-many-relationship">Complex使用的Rails的ActiveRecord上的许多查询到很多关系

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

或者这样:的http://blog.hasmanythrough.com/2006/6/12/when-associations-arent-enough-part-2

推荐答案

修改有(​​'COUNT(*)=?,则params [:搜索] [:amenity_ids] .reject(安培;: ?空白)尺寸)有(​​'COUNT(*)&GT; =?,则params [:搜索] [:amenity_ids] .reject(安培;:空白? ).size)(即 = &GT; = )修复该问题。

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.

但现在还有另一个问题:<一href="http://stackoverflow.com/questions/33452977/ruby-on-rails-query-yielding-unexpected-results">Ruby on Rails的收益进行查询意想不到的效果。

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

这篇关于Ruby on Rails的查询不工作正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆