Dec 12, 2009

Reject/Ignore/Stop Rails Active Record Callbacks Selectively

Faced a small issue today. I had a model in rails; where Model had :before_save filter set for the model. To make things more complex before_save had not one, but several invocations.

Unfortunately one of those invocations went about fetching a service instance from injected spring context. This really pissed off a database migration script; because it didn't have spring context.

So effectively I needed to ignore that particular before_save callback. After a bit of googling I found the solution.

If you want to skip all the callbacks on a particular model; use following statement:
MyModel.before_save.clear

or to skip a particular method invocation following statement can be used:
MyModel.before_save.reject! {|callback| callback.method == :method_name}

This would skip the call to particular method invocation. It's particularly helpful in
  1. Rake Tasks, where you may not want some of the filters/callbacks to run as they do in actual code.
  2. Database Migration scripts
There can be other reasons; why you may want them to be skipped. Whatever works for you man..


No comments:

Post a Comment