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.
3 Answers
The failing validations add to the errors for the record, so you could just check:
return false unless self.errors.empty?
1 Comment
Artem Kalinchuk
I have tried this before and it still failed. Then I checked the code and I noticed that I was calling the validation again (when I wasn't supposed to). Now it works perfect. Thank you!
Have you thought about using the before_save callback instead?
I believe that will only be called if the object is valid.
2 Comments
Artem Kalinchuk
What if I don't want to save it? Just want to validate it?
Matt Huggins
You also can't do more advanced things in
before_save like checking what fields changed in an association (via xxx_changed?) since the associations get updated first, thereby resetting the changed hash. As such, it's necessary to perform these checks in after_validation as a workaround.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.
errors, likereturn false unless self.errors.empty?orreturn false if errors.any?.