I am new to Rails and using this code to update or insert.
user = User.find_by_email(params[:email])
if user.nil?
User.create!(params)
else
user.save(params)
end
// params is a hash with keys as table columns
This code is not working. Also, I would like to know if Rails has something magical to do this in one line ?
I’ve not declared email as primary key but its going to be unique. Will it help me to declare it as primary ?
Your code doesn’t work because the parameter to
saveis as a hash of options (such as should validations run), not the changes to the attributes. You probably wantupdate_attributes!instead. I would usually write something like