Artem Kalinchuk
Artem Kalinchuk

Reputation: 6652

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.

Upvotes: 22

Views: 8440

Answers (3)

Chap
Chap

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

Kevin Murani
Kevin Murani

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

asc99c
asc99c

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

Related Questions