Why does my rails rollback when I try to user.save?
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.
When save rollbacks, use save! instead, and error log will be printed.
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.
After you try to save or validate an active record model instance you can view more information about what happened with a few useful commands.
user = User.find(108)
user.name = "Larry"
user.valid? # returns false
user.errors.messages # returns something like {email: "Cant be blank"}
Obviously I made that error up because I don't know what your model file looks like but if it roles back its for one of two reasons usually. The first is your validations failed. If their are no error messages its probably because something in your filter chain returned false. For example
class User << ActiveRecord::Base
before_save :accidentally_return_false
def accidentally_return_false
self.some_boolean = (condition == value)
end
end
user = User.new( params )
user.save # where condition does not equal value
user.valid? # false because of the before save method
Hope that helps