Reputation: 6652
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.
Upvotes: 22
Views: 8440
Reputation: 3553
Have you thought about using the before_save
callback instead?
I believe that will only be called if the object is valid.
Upvotes: 4
Reputation: 186
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.
Upvotes: 1
Reputation: 3905
The failing validations add to the errors for the record, so you could just check:
return false unless self.errors.empty?
Upvotes: 27