The Order of Rails Validation Filters

Here are the available Rails validation filters:

before_validation_on_update
before_validation_on_create
validate
validate_on_update
validate_on_create
after_validation
after_validation_on_update
after_validation_on_create
before_save
before_update
before_create
after_update
after_create
after_save



These filters are callbacks that are invoked automatically.

The difference between update and create is really with respect to the database. If the record you are saving is a new record in the db, then it means you are creating. If the item already exists but you are making a change, then it means you are updating. In other words, it does not matter, whether you called obj.save or obj.create, before_update filter will be invoked. The same is true for obj.save vs. obj.update_attributes. So no matter what Active record method you invoke the filter is decided based on the database record.

How about before_save, before_after_save? They will always be invoked whether you are creating or updating.

In the light of this information, the order of these filter is as follows:

  1. before_validation
  2. before_validation_on_update or before_validation_on_create
  3. validate
  4. validate_on_update or validate_on_create
  5. after_validation
  6. after_validation_on_update or after_validation_on_create
  7. before_save
  8. before_update or before_create
  9. after_update or after_create
  10. after_save

Note that before_save is invoked before before_update and before_create, while after_save is invoked after after_update and after_create.

Comments

deezzer said…
This comment has been removed by the author.
deezzer said…
Great insight. I was thinking before_save would be invoked if you created a new record using @object.save and before_create would be if you used Object.create()

I appreciate that Rails makes this indifferent. I mean, is it realistic that coders are consistent with the methods they use to create/save new objects? No way!

Thanks for clarifying.
Anonymous said…
This comment has been removed by the author.