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.
Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.
Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.
Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. Model-level validations are the best way to ensure that only valid data is saved into your database.
The failing validations add to the errors for the record, so you could just check:
return false unless self.errors.empty?
Have you thought about using the before_save callback instead?
I believe that will only be called if the object is valid.
I know this is an old question but I ran into the same error when using a custom validation on a model I had created. Looking at the docs there's a part covering custom methods and it states that such validations are called each time the .valid?
method. That's probably why the infinite loop got triggered when the :after_validation
callback was triggered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With