Why does my rails rollback when I try to user.save?

前端 未结 8 1060
北荒
北荒 2020-12-12 16:17

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

相关标签:
8条回答
  • 2020-12-12 17:03

    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

    0 讨论(0)
  • 2020-12-12 17:05

    When save rollbacks, use save! instead, and error log will be printed.

    0 讨论(0)
提交回复
热议问题