我有過濾產品通過精確的標籤問題,因爲我目前的查詢不返回精確匹配,我似乎無法得到正確的查詢條件很多。Rails的多個連接的確切標籤條件的查詢與具有通過關係
例
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?