I was wondering in what order are callbacks and validations called when an ActiveRecord object is created.
Let’s say I have some custom validations & callbacks like the following:
validates :reference_code, :if => :reference_code, :on => :create
before_create :assign_reference
which one will run first? The callback needs to happen first or else the validation may fail.
The most-up-to-date version of this list for the latest version of Rails can be found in the
ActiveRecord::Callbacksdocumentation. The lists for Rails 4, 3 & 2 are below.Rails 4
The most up-to-date version of this list can be found in the Rails 4 Guides.
Creating an object
before_validationafter_validationbefore_savearound_savebefore_createaround_createafter_createafter_saveafter_commit/after_rollbackUpdating an object
before_validationafter_validationbefore_savearound_savebefore_updatearound_updateafter_updateafter_saveafter_commit/after_rollbackDestroying an object
before_destroyaround_destroyafter_destroyafter_commit/after_rollbackRails 3
The most up-to-date version of this list can be found in the Rails 3 Guides.
Creating an object
before_validationafter_validationbefore_savearound_savebefore_createaround_createafter_createafter_saveUpdating an object
before_validationafter_validationbefore_savearound_savebefore_updatearound_updateafter_updateafter_saveDestroying an object
before_destroyaround_destroyafter_destroyRails 2
The most up-to-date version of this list can be found in the Rails 2.3 Guides
Creating an object
before_validationbefore_validation_on_createafter_validationafter_validation_on_createbefore_savebefore_createINSERToperationafter_createafter_saveUpdating an object
before_validationbefore_validation_on_updateafter_validationafter_validation_on_updatebefore_savebefore_updateUPDATEoperationafter_updateafter_saveDestroying an object
before_destroyDELETEoperationafter_destroySince you need to first validate the
reference_code, theassign_referencemethod can be called in theafter_validationcallback or any callback appearing after it in the list I provided above.