All objects created in a rails application have a life cycle, which consists of three general stages: Create, Update, and Destroy. Callbacks allow you to trigger designated methods before, during, or after each stage of an objects life cycle.
Below I will go over some of the basics of an objects lifecycle, as well as a few callback methods and the order in which they will be called.
Create
Object.create
While this one method may seem to only be creating a new object and saving it to the database, there are actually many steps taking place under the hood to achieve this.
- Before the object is created it needs to pass its validations.
- After the object is validated it is given the okay to be created.
- After creation the item is finally saved to the database
Before, during, and after each of these steps takes places we are able to utilize callback methods to perform actions.
Callback methods for Create
- before_validation
- after_validation
- before_save
- before_create
- after_create
- after_save
In order to demonstrate the order the above callbacks are called in we can define a simple user model with a method that puts
out the name of each callback.
class User < ApplicationRecord
before_validation :bv
after_validation :av
before_save :bs
before_create :bc
after_create :ac
after_save :as
after_commit :a_com
def bv
puts "before_validation"
end
def av
puts "after_validation"
end
def bs
puts "before_save"
end
def bc
puts "before_create"
end
def ac
puts "after_create"
end
def as
puts "after_save"
end
Once we create an instance of the user model we can see in the console the order in which the methods are being called as the item is created and then saved to the database.
Update
Object.update
Callback methods for Update
- before_validation
- after_validation
- before_save
- before_update
- after_update
- after_save
Callback methods for Update behave very similarly to the create callbacks.
- Note:
after_save
runs both on create and update, but always after the more specific callbacksafter_create
andafter_update
Destroy
Object.destroy
Callback methods for Destroy
- before_destroy
- after_destroy
Conclusion
There are many uses for callbacks, which are covered in greater detail at the Ruby on Rails guide.
I encourage anyone creating a Rails project to look into them further and utilize there powerful features!
Top comments (0)