Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: "find_create_by_user"

I'm wondering why this is not working for me:

Recipe.find_or_create_by_user_id(current_user.id, :name => "My first recipe")

That creates the recipe fine if one does not exist by the user's id, but the name ("My first recipe") isn't included into the newly created entry. Is there something I'm doing wrong? I can't quite figure this one out.

like image 431
Drew Avatar asked Aug 07 '26 20:08

Drew


1 Answers

Try it this way:

Recipe.find_or_create_by_user_id(current_user.id) do |recipe|
  recipe.name = 'My first recipe'
end

The block will only get called if it has to create the record.

like image 188
tadman Avatar answered Aug 10 '26 12:08

tadman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!