3

According to this answer, the custom validation fails when the method return true.

I want to know if this is mentioned in official docs? The rails guide only mention errors.add as a way to trigger custom validation method to fail.

Community
  • 1
  • 1
Heisenberg
  • 8,386
  • 12
  • 53
  • 102
  • I think you are wrong. The returned value means nothing in case of custom validation. Can you show an example that confirms your statement ? – chumakoff Aug 17 '15 at 22:29
  • How would you interpret the linked answer? How does the custom validation method fail in that example? – Heisenberg Aug 18 '15 at 00:25
  • 2
    The linked answer has nothing to do with your problem. In the example `return` means that you exit the method, the returned value is nil, no errors are added, the validation succeeds. – chumakoff Aug 18 '15 at 08:30

1 Answers1

4

It depends how you are using your custom validations.

If you are using Active Record Callbacks, i.e. before_save or before_validation, if you return false from any of these, your validation will FAIL and the record will not be saved: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#module-ActiveRecord::Callbacks-label-before_validation-2A+returning+statements

However if you are using a custom validator such as mentioned here: http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations the return value is not significant (It is not mentioned in the docs, as you say), what matters is if you add to the errors array.

aaron-coding
  • 2,571
  • 1
  • 23
  • 31
  • Just note that from Rails 5 onwards, the `return true` method does not work, you'll need to `throw :abort` instead. https://guides.rubyonrails.org/active_record_callbacks.html#halting-execution – brod Sep 02 '22 at 10:02