Search code examples
ruby-on-railsrubyvalidation

Ruby on Rails - after_validation if valid?


Right now, from what I know, after_validation will be called even if the model fails the validations. Is there a way to only call it if the model is valid? I tried adding return false unless self.valid? in the after_validation method but that triggers validation again and it creates an infinite loop.


Solution

  • The failing validations add to the errors for the record, so you could just check:

    return false unless self.errors.empty?