I noticed that Rails doesn't trigger after_initialize
callback when the callback symbol is passed as input.
The code below doesn't work.
class User < ActiveRecord::Base
after_initialize :init_data
def init_data
puts "In init_data"
end
end
The code below works.
class User < ActiveRecord::Base
def after_initialize
init_data
end
def init_data
puts "In init_data"
end
end
Can somebody explain this behavior?
Note 1
The ActiveRecord documentation says the following about after_initialize
:
Unlike all the other callbacks, after_find and after_initialize will
only be run if an explicit implementation is defined (def after_find).
In that case, all of the callback types will be called.
Though it is stated that after_initialize requires explicit implementation, I find the second sentence in the above paragraph ambiguous, i.e. In that case, all of
the callback types will be called.
What is all of the call back types
?
The code sample in the documentation has an example that doesn't use explicit implementation:
after_initialize EncryptionWrapper.new
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
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.
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.
According to the documentation, you cannot use the macro-style class methods for the after_initialize
or after_find
callbacks:
The after_initialize and after_find callbacks are a bit different from the others. They have no before_* counterparts, and the only way to register them is by defining them as regular methods. If you try to register after_initialize or after_find using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since after_initialize and after_find will both be called for each record found in the database, significantly slowing down the queries.
In short, you have to define an after_initialize
instance method:
class User < ActiveRecord::Base
def after_initialize
do_stuff
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