In my previous blog Rails Active Records Callbacks: Part 1, I explained about why these callbacks are required and also discussed about some of the useful methods available in rails active records during creation and saving of the objects. Today I will talk about some more callbacks available in active records. Few of them are:
Callbacks that are called during deletion of an object.
It gets called before the object is destroyed, It is used in a case such that if you want to retrieve few things before the object is removed.
It gets called along with the object is being destroyed. So it gets called between the before_destroy and after_destroy.
It gets called after the object is destroyed.
Lets take an example to understand how they are getting called:
class TestUser < ActiveRecord::Base
puts "Within Before Destroy"
puts "Within After Destroy"
puts "Within Around Destroy"
## Now try in console
u = TestUser.create(phone_number: "9876543210")
(0.2ms) begin transaction
SQL (0.6ms) INSERT INTO "test_users" ("phone_number", "created_at", "updated_at") VALUES (?, ?, ?) [["phone_number", "9876543210"], ["created_at", "2016-06-08 17:04:42.102906"], ["updated_at", "2016-06-08 17:04:42.102906"]]
(116.8ms) commit transaction
=> #<TestUser id: 3, phone_number: "9876543210", created_at: "2016-06-08 17:04:42", updated_at: "2016-06-08 17:04:42">
(0.1ms) begin transaction
Within Before Destroy
Within Around Destroy
Within After Destroy
(0.1ms) rollback transaction
Thus you have seen the order in which they gets called.
Suppose there are 2 related objects Company and Employee, So if company is destroyed after that you want to destroy all of its employees. So in this case there are relational callbacks that are used. So in this case we can specify the callback during specifying the relation like in our case:
class Company < ActiveRecord::Base
has_many :employees, dependent: :destroy
class Employee < ActiveRecord::Base
In above example dependent: :destroy works as an callback so it the company is removed all of its associated employees are also removed.
Hope you liked this blog. Will talk about some more active record related topics soon.