From the Rails Guides. Callbacks could hook into Active Record Object's life cycle. In the order of execution, they're (copied from Rails Guides):
before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
after_commit/after_rollback
before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save
after_commit/after_rollback
before_destroy
around_destroy
after_destroy
after_commit/after_rollback
I am wondering where to put the after_initialize
and after_find
into above? I think after_initialize
should put before before_validation
and after_find
does not belongs to any three of them. Am I correct? Thanks.
The after_initialize
and after_find
callbacks are the two special callbacks.
The only way to define callbacks for the after_find
and after_initialize
events is to define them as methods
. If you try declaring them as handlers
,they’ll be silently ignored.
From the API
after_find
andafter_initialize
callback is triggered for each object that is found and instantiated by a finder, withafter_initialize
being triggered after new objects are instantiated as well.
From the Guides
The
after_initialize
callback will be called whenever an Active Record object is instantiated, either by directly using new or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record initialize method.The
after_find
callback will be called whenever Active Record loads a record from the database.after_find
is called beforeafter_initialize
if both are defined.The
after_initialize
andafter_find
callbacks have no before_* counterparts, but they can be registered just like the other Active Record callbacks.class User < ActiveRecord::Base after_initialize do |user| puts "You have initialized an object!" end after_find do |user| puts "You have found an object!" end end >> User.new You have initialized an object! => #<User id: nil> >> User.first You have found an object! You have initialized an object! => #<User id: 1>
where to put the after_initialize
and after_find
in the AR object life cycle?
Since they are different from all other callbacks and also they don't have before_* counterparts,so the author(referring to Guides author here) might be interested in putting them separately as they are special case.
And finally I would agree with in putting after_initialize
before before_validation
. It might be the case.
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