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"开发者_StackOverflow中文版) isn't included into the newly created entry. Is there something I'm doing wrong? I can't quite figure this one out.
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.
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")
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.
精彩评论