Rails model.valid? flushing custom errors and falsely returning true

前端 未结 5 750
一向
一向 2021-01-07 16:56

I am trying to add a custom error to an instance of my User model, but when I call valid? it is wiping the custom errors and returning true.

[99] pry(main)&g         


        
5条回答
  •  太阳男子
    2021-01-07 17:20

    In ActiveModel, valid? is defined as following:

    def valid?(context = nil)
      current_context, self.validation_context = validation_context, context
      errors.clear
      run_validations!
    ensure
      self.validation_context = current_context
    end
    

    So existing errors are cleared is expected. You have to put all your custom validations into some validate callbacks. Like this:

    validate :check_status
    
    def check_status
      errors.add(:status, "must be YES or NO") unless ['YES', 'NO'].include?(status)
    end
    

提交回复
热议问题