【问题标题】:Rails multiple joins condition query for exact tags with has many through relationshipsRails 多个连接条件查询具有许多直通关系的确切标签
【发布时间】:2017-02-17 12:50:59
【问题描述】:

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

示例

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

产品A只有["small","smooth","rough"]作为标签

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

我有三个模型,ProductAreaSurfaceArea & 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


    【解决方案1】:

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

    首先,我使用 AreaSurface 的模型名称作为它们的唯一标识符,因为它们可能有冲突的 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-17
      • 2019-07-11
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 2012-05-28
      相关资源
      最近更新 更多