diff options
author | Pablo Ifran <pabloifran@gmail.com> | 2012-10-19 17:25:45 -0200 |
---|---|---|
committer | Pablo Ifran <pabloifran@gmail.com> | 2012-10-19 17:25:45 -0200 |
commit | d4db09514cc3f18d1d157caaf0784bedf38fafe8 (patch) | |
tree | 63dad5578fa65ec501dde99de7b5ce9264a066fa /activerecord/lib/active_record | |
parent | aee07fe135e5e41ff4fc0bc2e0e33d877cceda42 (diff) | |
download | rails-d4db09514cc3f18d1d157caaf0784bedf38fafe8.tar.gz rails-d4db09514cc3f18d1d157caaf0784bedf38fafe8.tar.bz2 rails-d4db09514cc3f18d1d157caaf0784bedf38fafe8.zip |
ActiveRecord Callbacks ordering examples
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r-- | activerecord/lib/active_record/callbacks.rb | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index 111208d0b9..9626df08aa 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/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 |