when is around_create callback code executed, in what situations we should use it?
Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
Active Record Callbacks are hooks to which we can register methods in our models. These hooks are executed in various stages of an Active Record object lifecycle. The following callbacks are run when an object is created. These callbacks are executed in the order in which they are listed below.
During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks (called callbacks) into this object life cycle so that you can control your application and its data. Callbacks allow you to trigger logic before or after an alteration of an object's state.
The callback order is as following:after_validation_on_create / after_validation_on_update. before_save. before_create.
Had this question, too, and have now found the answer: around_create
allows you to basically do both a before_create
and an after_create
in one method. You have to use yield
to execute the save in between.
class MyModel < ActiveRecord::Base
around_create :my_callback_method
private
def my_call_back_method
# do some "before_create" stuff here
yield # this makes the save happen
# do some "after_create" stuff here
end
end
Just found one use case for me:
Imagine a situation with polymorphic watcher and the watcher in some cases needs to perform action before save and in other cases after it.
With around filter you can capture save action in a block and run it when you need.
class SomeClass < ActiveRecord::Base
end
class SomeClassObserver < ActiveRecord::Observer
def around_create(instance, &block)
Watcher.perform_action(instance, &block)
end
end
# polymorphic watcher
class Watcher
def perform_action(some_class, &block)
if condition?
Watcher::First.perform_action(some_class, &block)
else
Watcher::Second.perform_action(some_class, &block)
end
end
end
class Watcher::First
def perform_action(some_class, &block)
# update attributes
some_class.field = "new value"
# save
block.call
end
end
class Watcher::Second
def perform_action(some_class, &block)
# save
block.call
# Do some stuff with id
Mailer.delay.email( some_class.id )
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With