Photo-1 Photo-2 Photo-3 Photo-4 Photo-5 Photo-6



Full-time web developer. Part-time smart ass.

I'm Brent Collier.

After a year and a half as an engineer on Twitter's Trust & Safety team, I'm looking for my next gig. Contact me if you know of something interesting.


Temporarily disable activerecord callbacks

Posted on 03/12/2009

ActiveRecord callbacks can be super-handy, but every once in a while, they get in the way.

I was recently working on an Intridea client project and I had to create a rake task to import a large set of data from a spreadsheet.  One of the models that was being imported had an after_save callback that sent out an email notification.  I didn't really want 3500 emails to be sent out whenever this rake task was ran, so I needed to disable the callback while the import task was running.

A former coworker, Blake, from NT showed me this trick...

Say you've got a model like so...

class Thing < ActiveRecord::Base
      before_save :do_stuff
      def do_stuff
        raise "This thing is doing stuff..."

In the config/initializers directory, I created a file called extensions.rb.  You can call it whatever you like.  I chose 'extensions' because I use the same file for any minor Ruby or Rails class extensions.  In it, I put this...

class ActiveRecord::Base
      def self.without_callback(callback, &block)
        method = self.send(:instance_method, callback)
        self.send(:remove_method, callback)
        self.send(:define_method, callback) {true}
        self.send(:remove_method, callback)
        self.send(:define_method, callback, method)

What this does is it grabs the callback and stores it in the method variable.  Remember, this code only circumvents the 'do_stuff' method, not anything declared as a before_save callback.  It then redefines the method to merely return true, yields to the block, and then redifines the the method with the contents of the method variable. 

Yielding to the block allows you to not have to worry about maintaining the method contents, or restoring it once you're done.  Also, if you were so inclined, you could easily modify this code to accept an array of method names and disable all of them

Once the extension is in place, you can do this...

Thing.without_callback(:do_stuff) do
      thing =

...without 'do_stuff' ever being called.

Some people will probably argue that if you need to disable your callback, then your model should be defined differently, but I say that's bullshit.  I think this is perfectly acceptable in many cases.  Granted you probably wouldn't want to do this all throughout your application code, but I see no problem with using this technique in a test, or data migration, or in my case, a rake task.


WOOT! Now there's a plugin. Check it out... without_callbacks