22

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.

1
  • 2
    Well, you could check for errors, like return false unless self.errors.empty? or return false if errors.any?. Commented Nov 4, 2011 at 13:48

3 Answers 3

27

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

return false unless self.errors.empty?
Sign up to request clarification or add additional context in comments.

1 Comment

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!
5

Have you thought about using the before_save callback instead?

I believe that will only be called if the object is valid.

2 Comments

What if I don't want to save it? Just want to validate it?
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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.