The Order of Rails Validation Filters
Here are the available Rails validation filters:
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:
Note that before_save is invoked before before_update and before_create, while after_save is invoked after after_update and after_create.
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:
- before_validation
- before_validation_on_update or before_validation_on_create
- validate
- validate_on_update or validate_on_create
- after_validation
- after_validation_on_update or after_validation_on_create
- before_save
- before_update or before_create
- after_update or after_create
- 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
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.