How can I pass multiple attributes to find_or_create_by in Rails 3?

后端 未结 5 1143
独厮守ぢ
独厮守ぢ 2020-12-12 20:53

I want to use find_or_create_by, but this statement does NOT work. It does not \"find\" or \"create\" with the other attributes.

productproperty = ProductPro         


        
5条回答
  •  孤城傲影
    2020-12-12 21:20

    See http://api.rubyonrails.org/classes/ActiveRecord/Base.html:

    With single query parameter:

    productproperty = ProductProperty.find_or_create_by_product_id(product.id) { |u| u.property_id => property_id, u.value => d[descname] } )
    

    or extended with multiple parameters:

    productproperty = ProductProperty.find_or_create_by_product_id(:product_id => product.id, :property_id => property_id, :value => d[descname]) { |u| u.property_id => property_id, u.value => d[descname] } )
    

    Would work with:

    conditions = { :product_id => product.id, 
                   :property_id => property.id,
                   :value => d[descname] }
    
    pp = ProductProperty.find(:first, :conditions => conditions) || ProductProperty.create(conditions) 
    

提交回复
热议问题