0

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

Area = ["small","big"]Surface = ["smooth","rough"]

產品A只有["small","smooth","rough"]作爲標籤

如果我篩選使用["small","big","smooth","rough"]作爲標籤的產品,我得到的產品A在我的搜索結果,但理想情況下,它不應該返回任何搜索結果。

我有三種型號,Product,AreaSurfaceArea & 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? 

回答

0

我剛纔解決了這個問題,這個解決方案。

首先,我所使用的模型的名字Area & Surface來作爲其唯一IDENTIFER,因爲他們可以有衝突ids並將它們添加到陣列中。

接下來,我通過產品環和創建的名稱identifers的陣列,並且比較這兩個陣列來檢查它們是否相交。交叉點意味着搜索過濾器是正確的匹配,我們將產品ID添加到第三個數組,該數組存儲所有product_ids,然後再進行查詢以獲得具有這些產品id的產品。

@area = Area.all 
area_ids = params[:area_ids] 
@uniq_names = @area.where(id: area_ids).collect { |m| m.name } 
@products.each do |product| 
    @names = product.areas.map { |m| m.name } 
    # if intersect, then we add them to filtered product 
    if (@uniq_names - @names).empty? 
     product_ids << product.id 
    end 
end 
@products = Product.where(id: product_ids) 
相關問題