相关领域的掠夺者 return

Ransacker return on related field

我正在尝试创建一个自定义洗劫者,returns 一个产品基于另一个(相关)table 中的一个属性。我的数据库模式是这样的:

-------------   --------------------
|products   |   |product_properties|   ------------
|-----------|   |------------------|   |properties|
|name       |---|value             |---|----------|
|description|   |product_id        |   |name      |
|etc...     |   |property_id       |   ------------
-------------   --------------------

class Product < ActiveRecord::Base
  has_many :product_properties
  has_many :properties, through: :product_properties

  Property.pluck(:id, :name).each do |id, name|
    ransacker name.to_sym, formatter: -> (value) { value.to_s.downcase } do |parent|
      product_properties = Arel::Table.new(:product_properties)
      Arel::Nodes::InfixOperation.new('AND',
        Arel::Nodes::InfixOperation.new('=',
          product_properties[:property_id], id
        ),
        product_properties[:value]
      )
    end
  end
end

class ProductProperty < ActiveRecord::Base
  belongs_to :product, inverse_of: :product_properties, touch: true
  belongs_to :property, inverse_of: :product_properties
end

class Property < ActiveRecord::Base
  has_many :product_properties
  has_many :products, through: :product_properties
end

正如您可能看到的那样,我想使用 ransack 来 select 所有具有特定 属性 且其值与通过 ransack 传入的谓词相匹配的产品,即如果我有宽度 属性 我想这样做

Product.ransack(width_eq: 100).result

而不是

Product.ransack(product_properties_value_eq: 100, product_properties_property_name_eq: 'width')

我走的路是否正确,如有任何帮助,我们将不胜感激。我一直在为这个问题而烦恼。

犯的错误是我需要使用Arel::Nodes.build_quoted(id)。显然,在 Rails 和 Arel 上使用更高版本时需要这样做。

Property.pluck(:id, :name).each do |id, name|
  product_properties = Arel::Table.new(:product_properties)

  ransacker name.to_sym, formatter: -> (value) { value.to_s.downcase } do |parent|
    Arel::Nodes::InfixOperation.new('AND',
      Arel::Nodes::InfixOperation.new('=',
        product_properties[:property_id], Arel::Nodes.build_quoted(id)
      ),
      product_properties[:value]
    )
  end
end