Skip to content
Browse files

ActiveRecord Callbacks ordering examples

  • Loading branch information...
1 parent aee07fe commit d4db09514cc3f18d1d157caaf0784bedf38fafe8 @elpic elpic committed Oct 19, 2012
Showing with 43 additions and 0 deletions.
  1. +43 −0 activerecord/lib/active_record/callbacks.rb
View
43 activerecord/lib/active_record/callbacks.rb
@@ -200,6 +200,49 @@ module ActiveRecord
# Callbacks are generally run in the order they are defined, with the exception of callbacks defined as
# methods on the model, which are called last.
#
+ # == Ordering callbacks
+ #
+ # Sometimes the code needs that the callbacks execute in a specific order. For example, a +before_destroy+
+ # callback (log_children in this case) should be executed before the children get destroyed by the
+ # dependant destroy option.
+ #
+ # Let's take at the code below:
+ #
+ # class Topic < ActiveRecord::Base
+ #
+ # has_many :children, dependant: destroy
+ #
+ # before_destroy :log_children
+ #
+ # def log_children
+ # children.each do |child|
+ # # Some child processing
+ # end
+ # end
+ #
+ # end
+ #
+ # In this case the problem is that when the +before_destroy+ is executed, the children are not available
+ # because the dependant destroy gets executed first. To solve this issue it is possible
+ # to use the +prepend+ option on the +before_destroy+ callback.
+ #
+ # class Topic < ActiveRecord::Base
+ #
+ # has_many :children, dependant: destroy
+ #
+ # before_destroy :log_children, prepend: true
+ #
+ # def log_children
+ # children.each do |child|
+ # # Some child processing
+ # end
+ # end
+ #
+ # end
+ #
+ # This way, the +before_destroy+ gets executed before the <tt>dependant: destroy</tt> is called, and
+ # the data is still available.
+ #
# == Transactions
#
# The entire callback chain of a +save+, <tt>save!</tt>, or +destroy+ call runs

0 comments on commit d4db095

Please sign in to comment.
Something went wrong with that request. Please try again.