I have installed the RailsTutorial sample app(the twitter like application) and am trying to understand why the following piece of console code does not update the database
Your user model probably has validations which are not satisfied. Since you've not posted those I'm unable to really solve your question. To make live easier you can debug why your user isn't willing to save.
Try running
user.errors.full_messages
which should give you a hint what's going wrong.
I know this is an old post, but hopefully this might help someone going through this tutorial in the future.
As the accepted answer expresses, this is due to validations which are not being satisfied. I ran into this issue as well and found that another workaround is to use the update_attribute
method on the user
object. For example, if you want to update the name
field of a user
object and have it automatically save to the database, without having to touch the virtual password
and password_confirmation
fields, use the following:
user.update_attribute(:name, "larry")
This will update the name
field only and save it to the database (no need to call the save
method), without having to touch the password
and password_confirmation
fields.
I had the same issue of the database rolling back my transactions in the console while I was trying to update the admin property on a user. If you are doing the Hartl rails tutorial, the issue is that if you type in user.errors.messages in the console, it will tell you that the password is too short. That is because in the model there is a password validation before it saves and hashes your password into the password_digest.
The work around to this is in the console perform your normal activity like setting user.admin = true, and then when you are done, enter user.password = "foobar", then enter user.password_confirmation = "foobar", and then when you perform user.save it will commit all your changes.
Try to update the database:
rails db:migrate
I had this same problem and no errors were being stored. It turned out that my before_save
function was returning false which resulted in the save being canceled (I guess? I'm new to rails).
I was trying to set the value of a boolean which could only be set once a file had been uploaded.
Here's what I was doing:
before_save :set_orientation
def set_orientation
# ...do stuff...
self[:is_landscape] = ratio > 1 # stores AND returns the boolean value!!
end
The last line in the function was also an implicit return which I did not mean to do. My solution was to make the return explicitly:
before_save :set_orientation
def set_orientation
# ...do stuff...
self[:is_landscape] = ratio > 1 # store the boolean value
return # now return
end
Your validations are not passing. You can do:
user.errors.full_messages
in the console after the failed save to see why.