Hi Friends,
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.
a) before_destroy:
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.
b) around_destroy:
It gets called along with the object is being destroyed. So it gets called between the before_destroy and after_destroy.
c) 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
after_destroy :call_after_destroy
before_destroy :call_before_destroy
around_destroy :call_around_destroy
before_update :call_this
def call_before_destroy
puts "Within Before Destroy"
end
def call_after_destroy
puts "Within After Destroy"
end
def call_around_destroy
puts "Within Around Destroy"
end
end
## 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">
u.destroy
(0.1ms) begin transaction
Within Before Destroy
Within Around Destroy
Within After Destroy
(0.1ms) rollback transaction
=> nil
Thus you have seen the order in which they gets called.
Relational Callbacks:
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
end
class Employee < ActiveRecord::Base
belongs_to :company
end
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.
0 Comment(s)