[英]Ransacker return on related field
I am trying to create a custom ransacker that returns a product based upon an attribute within another (related) table. 我正在尝试创建一个自定义ransacker,以基于另一个(相关)表中的属性返回产品。 My DB schema is as such: 我的数据库架构是这样的:
------------- --------------------
|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
As you may be able to see I want to use ransack to select all products that have a particular property with a value that matches the predicate passed in through ransack, ie if I had a width property I would like to do this 如您所见,我想使用ransack选择具有特定属性的所有产品,这些产品的值与通过ransack传递的谓词相匹配,即,如果我有width属性,我想这样做
Product.ransack(width_eq: 100).result
instead of 代替
Product.ransack(product_properties_value_eq: 100, product_properties_property_name_eq: 'width')
Am I going along the right tracks, and any help with this would be much appreciated. 我是否走在正确的轨道上,在此方面的任何帮助将不胜感激。 I have been pulling my hair out over this problem. 我一直在努力解决这个问题。
The mistake made is that I needed to use Arel::Nodes.build_quoted(id)
. 犯的错误是我需要使用Arel::Nodes.build_quoted(id)
。 Apparently this is required when using later versions on Rails and Arel. 显然,在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.