views:

61

answers:

1

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 = ProductProperty.find_or_create_by_product_id(:product_id => product.id, :property_id => property.id, :value => d[descname])

There seems to be very little, or no, information on the use of dynamic finders in Rails 3. "and"-ing these together gives me a an unknown method error.

UPDATE:

Originally I couldn't get the following to work. Please assume I'm not an idiot and "product" is an instance of Product AR model.

product.product_properties.find_or_create_by_property_id_and_value(:property_id => 1, :value => "X")

The error methods was:

no such keys: property_id, value

I couldn't figure that out. Only this morning did I find the reference to passing the values like this instead:

product.product_properties.find_or_create_by_property_id_and_value(1, "X")

And voilá, it works fine. I would have expected a hash to work in the same situation but I guess not.

So I guess you get a down vote if you miss something on the internet?

+1  A: 
Lichtamberg
Sorry made a mistake, corrected it now.
Lichtamberg
But this will search only by `product_id` and when found/created will set the `property_id` and `value`. I guess @AKWF wants to search by all 3 values.
Matt
This works with multiple parameters too... Updated my post
Lichtamberg
This is only necessary if `property_id` and `value` are protected attributes. If not his statement above should work like expected. From the API: *Protected attributes won’t be set unless they are given in a block.*
captaintokyo
Your last update is nonsense... read the API again carefully ;-)
captaintokyo
you are right... damn ^^
Lichtamberg
But now `pp` will be `nil` if the records *does* exist. Don't think it can be made into a one-liner...
captaintokyo
Thx for the hint ^^
Lichtamberg
If you use `where(conditions).first` instead of `find(conditions)`, and `||` instead of `||=` it's perfect... `find(conditions)` doesn't work in Rails3. Almost there ;-)
captaintokyo
+1 Good call on using `||`. Although apparently you can also do: `pp = ProductProperty.find_or_create_by_product_id_and_property_id_and_value(product.id, property.id, d[descname])`
captaintokyo
oh.. yeah ^^ cool syntax ^^
Lichtamberg