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

后端 未结 5 1135
独厮守ぢ
独厮守ぢ 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:36

    If you want to search by multiple attributes, you can use "and" to append them. For example:

    productproperty = ProductProperty.find_or_create_by_product_id_and_property_id_and_value(:product_id => product.id, :property_id => property.id, :value => d[descname])
    

    There is one minor catch to be aware of. It will always return the object you've specified, even if that object can't be saved due to validation errors. So make sure you check to see if the returned object has an id (or is_valid?). Don't assume its in the database.

    Alternatively, you can use the 'bang' version of the method to raise an error if the object cannot be saved:

    http://guides.rubyonrails.org/active_record_querying.html#find-or-create-by-bang

    This applies to Rails 3.

提交回复
热议问题