Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens between after_validation and before_save?

The after_validation callback is triggered before before_save. What happens between those callbacks, if anything? Why would one choose one over another?

like image 494
bevanb Avatar asked Feb 11 '13 00:02

bevanb


2 Answers

There is an after_validation_on_update or after_validation_on_create depending if the item is a new record.

And as Max states, the chain is interrupted before it reaches the before_save callback if the object is not valid, so if you need something to occur regardless of the validity of the object before_save is not the place for it.

For reference: http://apidock.com/rails/ActiveRecord/Callbacks/after_validation_on_create

like image 123
Matt Avatar answered Oct 08 '22 18:10

Matt


after_validation_on_create and after_validation_on_update were removed from Rails 3.0.

New syntax form:

after_validation
after_validation, on: :update  # or :update
after_validation, on: [ :create, :update ]

Now nothing is executed between them.

Adding excellent comments to an answer:

"after_validation will be called if you call #valid? so there may be instances where you only want to check the validity of a record but still run something after validation. In my experience, I've never had a chance to use after_validation." @jvnill

"In addition to what jvnill said, an object is not saved if it is not valid. Therefore, calling save on an invalid object will not trigger the before_save callback, whereas it will trigger after_validation." @Max

like image 21
Andre Figueiredo Avatar answered Oct 08 '22 17:10

Andre Figueiredo