Whenever you create,save or initialize an object there are so many things available in rails that are called Callbacks or Hooks. They can be used as checks between on stage of the object to another. In this chapter I am going to explain few of the callbacks available during creation and saving of the object. One by one I will explain each of them a bit. But before that lets see the use case of why callbacks are an important feature in rails active records.
For example suppose you want to save phone number of a user and the user is free to enter the phone number either without any country code prefix or with country code prefix. So you want to check if the number is with country code you save it as it is in the db and if it is without country code you automatically add the country code before the number is even validated by its validates method. For fulfilling this use case their is a callback before_validation so if you pass a method inside before_validation it will be called before the validates of the model is called and you can write whatever code you want. Like in our case:
class User < ActiveRecord::Base
validates :phone_number, presence: true
if phone_number.present? && (!phone_number.starts_with? '+91')
self.phone_number = '+91'+self.phone_number
Thus you have seen that +91 is automatically appended to the number. Similar to this there are so many other validations available in rails. In this chapter I am explaining those methods that comes into picture during creation or saving of a record:
It is called before the validates are called.
It is called after all the validations are performed but the objects is still not saved.
It is called after the validations are performed and also the after_validates methods are executed but the object is still not saved. It gets called every time before the object is saved, either it is new or old.
This method is also called at the same time after the validations are performed and also the after_validates methods are executed. But this gets called only when the object is newly created and not a persisted one.
methods passed under around_save gets called during the object is being saved.
It gets called before any update call is made to an existing object.
Methods passed under around_update gets called during the object is being updated.
Similar to around_save, except it is called only during creation of a new record not a persisted one.
It gets called after the object is saved. It works for both the new and persisted records.
It gets called after the object is created. Works only for new records.
It works after the object is updated.
These callback operations are performed when the objects are successfully replicated into the DB or removed from DB.
Hope you liked this blog. In my next blog I will write some other types of useful callbacks of active records.