views:

68

answers:

3

Hello,

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.

+3  A: 

You can try this a couple of different ways:

Recipe.find_or_create_by_user_id_and_name(current_user.id, "My first recipe")

Recipe.find_or_create_by_user_id(:user_id => current_user.id, :name => "My first recipe")
Michael Sepcot
Thanks, Michael. What if the user decides to change the recipe's name in the future though?
Drew
+6  A: 

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.

tadman
Thanks Tadman. I had no idea. Thanks so much!
Drew
+1  A: 

Is there any chance you're using attr_accessible or attr_protected in your Recipe model? If name is not accessible, then when you pass it in via mass assignment, it won't get assigned as expected.

I believe that would explain why tadman's method works and your original attempts did not. If name is not something that you have serious security concerns around, you might consider exposing it via attr_accessible.

Kyle