[英]Ransacker return on related field
我正在尝试创建一个自定义ransacker,以基于另一个(相关)表中的属性返回产品。 我的数据库架构是这样的:
------------- --------------------
|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选择具有特定属性的所有产品,这些产品的值与通过ransack传递的谓词相匹配,即,如果我有width属性,我想这样做
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.