簡體   English   中英

蘭薩克返回相關領域

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM