In ROR, the lifecycle of an object is attached to the database of the application. Objects are created in memory first then later stored in the database.
An object have following lifecycle
- Creation
- Validation
- Save
- Update
- Deletion
These lifecycle have callbacks attached to each of them by which we can inject our custom logic.
Creation callbacks
- before_create
- after_create
- around_create
- before_save
- after_save
- around_save
Validation callbacks
- before_validation
- after_validation
Validation callbacks get execute whenever a new object is saved or it gets updated
Save callbacks
- before_save
- after_save
- around_save
Save callbacks will called for both Model.create and Model.save methods
Update callbacks
- before_update
- after_update
- around_update
Delete object callbacks
- before_destory
- after_destroy
- around_destroy
Sequence in which callbacks gets called.
For Creating an object.
Following sequence of callbacks get called when Model.create is invoked.
- before_validation
- after_validation
- before_save
- around_save
- before_commit
- before_create
- around_create
- after_create
- after_save
- after_commit
For Updating an object
Following sequence of callbacks get called when Model.update is invoked.
- before_validation
- after_validation
before_save
- around_save
- before_commit
- before_update
- around_update
- after_update
- after_save
- after_commit
For deleting an object
Following sequence of callbacks get called when Model.destroy is invoked.
- before_destroy
- around_destroy
- after_destroy
- after_commit
Read Also: Demystifying ActiveRecord query generation – Arel
Observations:
- after_commit is always called in the end
- before_commit gets called before_update, before_save and before_create
- before_validation and after_validation will executed before any other callbacks
- around_* callbacks are called after before_* callbacks
- General sequence, before_save, around_save, before_commit, before_create/update, around_create/update
- After sequence follows, after_create/update, after_save, after_commit