Ruby on Rails: "find_create_by_user"

I am wondering why this is not working for me:

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

      

This creates the recipe in order if it does not exist by user id, but the name ("My first recipe") is not included in the newly created entry. Is there something I am doing wrong? I cannot figure it out.

+2


source to share


3 answers


Try this:

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

      



The block will be called only if it needs to create a record.

+6


source


You can try this in several 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")

      

+3


source


Is there a chance you are using attr_accessible or attr_protected in your recipe model? If the name is not available then when you pass it through bulk assignment it will not be assigned as expected.

I believe this will explain why the tadman method works and your initial attempts did not. If the name is not something serious security related, you can consider it through attr_accessible.

+1


source







All Articles