Techie November 2022
Definition
Callbacks are methods that are called at some points of an object’s lifecycle. They are basically code that will execute before we can respond to a request. Callbacks are always called before particular controller actions (usually listed on top of the file). The reason for this is that you need to find an object from the database and assign it to an instance variable in all those actions.
Callbacks are private because we dont want to access these actions outside the class.
A callback method is meant to keep the code DRY (Do not Repeat Yourself), because if you don’t have a private method for this, you would have to copy/paste the line inside the method for each controller action. Which is fine as long as you don’t need to change it EVER. That is why it is good practice to use callbacks for these kinds of methods.
Example
Callback Types
On Object Initialized
- after_initialize
Before Transaction is Committed
- before_validation
- after_validation
- before_save
- around_save
- after_save
- before_create
- around_create
- after_create
On Rollback
- after_rollback
After Transaction is Committed Successfully
- after_create_commit
- after_commit
Order of Operations
Creating an Object
- before_validation
- after_validation
- before_save
- around_save
- before_create
- around_create
- after_create
- after_save
- after_commit/after_rollback
Updating an Object
- before_validation
- after_validation
- before_save
- around_save
- before_update
- around_update
- after_update
- after_save
- after_commit/
after_rollback
Destroying an Object
- before_destroy
- around_destroy
- after_destroy
- after_commit/
after_rollback
Thanks for reading, see you in the next one!