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

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.


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