4

I have an after_save filter which I dont want to trigger in a specific instance. Is there a way to do this similar to save_without_validation?

Thanks,

4 Answers4

1

When using rails 2, you can invoke the private method create_without_callbacks by doing:

@my_obj.send(:create_without_callbacks)
rafamvc
  • 8,227
  • 6
  • 31
  • 34
brad
  • 31,987
  • 28
  • 102
  • 155
0

There is a good example of extending ActiveRecord to provide callback skipping here: http://weareintegrum.com/?p=10

The idea is to create a method on ActiveRecord called skip_callback that accepts a block:

def self.skip_callback(callback, &block)
  method = instance_method(callback)
  remove_method(callback) if respond_to?(callback)
  define_method(callback){ true }
  begin
    result = yield
  ensure
    remove_method(callback)
    define_method(callback, method)
  end
  result
end

Then anything you do within the block does not execute the callback.

Michael Sepcot
  • 11,235
  • 3
  • 23
  • 19
0

You can set and reset callbacks like this:

  Post.after_update.reject! {|callback| callback.method.to_s == 'fancy_callback_on_update' }
  Post.after_create.reject! {|callback| callback.method.to_s == 'fancy_callback_on_create' }

  Post.after_create :fancy_callback_on_create
  Post.after_update :fancy_callback_on_update

You can add these around your custom save method.

Swanand
  • 12,317
  • 7
  • 45
  • 62
0

For Rails 2, you can also use the following methods:

create_without_callbacks or update_without_callbacks

rafamvc
  • 8,227
  • 6
  • 31
  • 34