Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 424
Artem Kalinchuk Avatar asked Nov 04 '11 13:11

Artem Kalinchuk


People also ask

What is validation in rails?

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.

Can we save an object in the DB if its validation do not pass?

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.

What is validate in Ruby on Rails?

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.


3 Answers

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

return false unless self.errors.empty?
like image 136
asc99c Avatar answered Oct 05 '22 05:10

asc99c


Have you thought about using the before_save callback instead?

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

like image 35
Chap Avatar answered Oct 05 '22 05:10

Chap


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.

like image 35
Kevin Murani Avatar answered Oct 05 '22 07:10

Kevin Murani