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

前端 未结 5 749
一向
一向 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:25

    If you want to force your model to show the errors you could do something as dirty as this:

    your_object = YourModel.new 
    your_object.add(:your_field, "your message")
    your_object.define_singleton_method(:valid?) { false }
    # later on...
    your_object.valid?
    # => false
    your_object.errors
    # => {:your_field =>["your message"]} 
    

    The define_singleton_method method can override the .valid? behaviour.

提交回复
热议问题