In rails, how can I find out what caused a .save() to fail, other than validation errors?

前端 未结 5 1224
天涯浪人
天涯浪人 2020-12-24 11:18

I have an ActiveRecord model which is returning true from valid? (and .errors is empty), but is returning false from save()

相关标签:
5条回答
  • 2020-12-24 11:46

    If @user.save (for example) returns false, then just run this to get all the errors:

    @user.errors.full_messages
    
    0 讨论(0)
  • 2020-12-24 11:53

    Try using the bang version save! (with an exclamation mark at the end) and inspecting the resulting error.

    0 讨论(0)
  • 2020-12-24 11:58

    Yea, I fixed this issue by making sure I return true in all my before_* callbacks then it starts working :)

    0 讨论(0)
  • 2020-12-24 12:01

    Check all your callbacks.

    I had a problem like this where I had and "after_validate" method that was failing after I had made a bunch of changes to the model. The model was valid but the "after_validate" was returning false, so if I used model.valid it said true, but then if I saved it gave me validation errors (passed through from the after_validate callback). It was weird.

    Look at the application trace and you should be able to see what line of code is raising the exception.

    0 讨论(0)
  • 2020-12-24 12:04

    The problem I had was that I had forgotten to add the validation to the model.

    class ContactGroup < ActiveRecord::Base
      validates_presence_of :name
    end
    
    0 讨论(0)
提交回复
热议问题