【发布时间】:2017-02-17 12:50:59
【问题描述】:
我在按确切标签过滤产品时遇到问题,因为我当前的查询没有返回完全匹配,而且我似乎无法获得正确的查询条件。
示例
Area = ["small","big"],Surface = ["smooth","rough"]
产品A只有["small","smooth","rough"]作为标签
如果我使用["small","big","smooth","rough"] 作为标签过滤产品,我会在搜索结果中获得产品 A,但理想情况下,它不应该返回任何搜索结果。
我有三个模型,Product、Area 和 Surface。 Area & Surface 通过has_many through 关系链接到Product。
class Product < ActiveRecord::Base
has_many :product_areas
has_many :areas, :through => :product_areas
has_many :product_surfaces
has_many :surfaces, :through => :product_surfaces
class Area < ActiveRecord::Base
#Surface model looks exactly the same as Area model
has_many :product_areas,dependent: :destroy
has_many :products, :through => :product_areas
我的查询
area_ids = params[:area_ids]
surface_ids = params[:surface_ids]
@products = Product.where(nil)
@products = @products.joins(:areas).where('areas.id' => area_ids).group('products.id').having("count(areas.id) >= ?",area_ids.count) unless area_ids.blank?
@products = @products.joins(:surfaces).where('surfaces.id' => surface_ids).group('products.id').having("count(surfaces.id) >= ?",surface_ids.count) unless surface_ids.blank?
【问题讨论】:
标签: sql ruby-on-rails-4 rails-activerecord active-record-query