Code Like Zell

Rails callback order

Posted 20 July 2009.

Here is a snippet to print the name of the Rails callback when called, as well as the receiving class:

  # Tested on Rails 2.3.8, put me in the config/initializers directory
  module ActiveRecord
    module Callbacks
      private

      alias :callback_orig :callback
      def callback(method)
        $stdout.puts "#{self.class.name} #{method}"
        callback_orig(method)
      end
    end
  end

Now to test it out, let’s create a couple models:

  ~$ script/generate model Foo 
  ~$ script/generate model Bar foo_id:integer
  ~$ rake db:migrate

Set their associations:

  class Foo < ActiveRecord::Base
    has_many :bars
  end  

  class Bar < ActiveRecord::Base
    belongs_to :foo
  end

Then start script/console and instantiate and save them:

  f = Foo.new
  f.bars.build
  f.save

The result for this situation was:

  Foo before_validation
  Foo before_validation_on_create
  Bar before_validation
  Bar before_validation_on_create
  Bar after_validation
  Bar after_validation_on_create
  Foo after_validation
  Foo after_validation_on_create
  Foo before_save
  Foo before_create
  Foo after_create
  Bar before_validation
  Bar before_validation_on_create
  Bar after_validation
  Bar after_validation_on_create
  Bar before_save
  Bar before_create
  Bar after_create
  Bar after_save
  Foo after_save

I’m not sure why the Bar validation callbacks are called twice.

All CLZ Posts

Hide this
Joypad Banner