Rails多个连接条件查询精确标签与多个关系

时间:2017-02-17 12:51:00

标签: sql ruby-on-rails-4 rails-activerecord active-record-query

我在使用精确标记过滤产品时遇到问题,因为我当前的查询没有返回完全匹配,我似乎无法获得正确的查询条件。

示例

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

产品A只有["small","smooth","rough"]作为代码

如果我使用["small","big","smooth","rough"]作为代码过滤产品,我会在搜索结果中获得产品A,但理想情况下,它不会返回任何搜索结果。

我有三个模型,ProductAreaSurfaceArea& Surface通过Product关系与has_many through相关联。

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?

1 个答案:

答案 0 :(得分:1)

我刚才用这个解决方案解决了这个问题。

首先,我使用了Area&amp;的模型名称。 Surface作为唯一标识符,因为它们可能存在冲突ids并将它们添加到数组中。

接下来,我浏览了产品并创建了一个名称标识符数组,并比较了两个数组以检查它们是否相交。交叉意味着搜索过滤器是正确的匹配,我们将产品ID添加到第三个数组,该数组存储所有product_id,然后再进行查询以获取具有这些产品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)
相关问题