ruby on rails - after_initialize & after_find callbacks order in Active Record object life cycle? -
from rails guides. callbacks hook active record object's life cycle. in order of execution, they're (copied rails guides):
creating object
before_validationafter_validationbefore_savearound_savebefore_createaround_createafter_createafter_saveafter_commit/after_rollback
updating object
before_validationafter_validationbefore_savearound_savebefore_updatearound_updateafter_updateafter_saveafter_commit/after_rollback
destroying object
before_destroyaround_destroyafter_destroyafter_commit/after_rollback
i wondering put after_initialize , after_find above? think after_initialize should put before before_validation , after_find not belongs 3 of them. correct? thanks.
the after_initialize , after_find callbacks 2 special callbacks.
the way define callbacks after_find , after_initialize events define them methods. if try declaring them handlers,they’ll silently ignored.
from api
after_find,after_initializecallback triggered each object found , instantiated finder,after_initializebeing triggered after new objects instantiated well.
from guides
the
after_initializecallback called whenever active record object instantiated, either directly using new or when record loaded database. can useful avoid need directly override active record initialize method.the
after_findcallback called whenever active record loads record database.after_findcalled beforeafter_initializeif both defined.the
after_initialize,after_findcallbacks have no before_* counterparts, can registered other active record callbacks.class user < activerecord::base after_initialize |user| puts "you have initialized object!" end after_find |user| puts "you have found object!" end end >> user.new have initialized object! => #<user id: nil> >> user.first have found object! have initialized object! => #<user id: 1>
where put after_initialize , after_find in ar object life cycle?
since different other callbacks , don't have before_* counterparts,so author(referring guides author here) might interested in putting them separately special case.
and agree in putting after_initialize before before_validation. might case.
Comments
Post a Comment