2015-10-29 180 views
0

我想創建一個自定義的ransacker,返回基於另一個(相關)表內的屬性的產品。我的數據庫架構是這樣的: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 

正如你可以看到我想用洗劫來選擇與匹配,通過搜查傳入的謂詞,也就是說,如果一個值的特定屬性的所有產品我有一個width屬性我想這樣做的這個

Product.ransack(width_eq: 100).result 

代替

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

上午我沿着正確的軌道去,任何幫助,將不勝感激。我一直在解決這個問題。

回答

0

所犯的錯誤是我需要使用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