Jason White
Jason White

Reputation:

Rails: Is there an equivalent to save_without_validation which skips after_save filters?

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,

Upvotes: 4

Views: 1218

Answers (4)

brad
brad

Reputation: 32345

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

@my_obj.send(:create_without_callbacks)

Upvotes: 1

Garrett Lancaster
Garrett Lancaster

Reputation: 260

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

create_without_callbacks or update_without_callbacks

Upvotes: 0

Swanand
Swanand

Reputation: 12426

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.

Upvotes: 0

Michael Sepcot
Michael Sepcot

Reputation: 11385

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.

Upvotes: 0

Related Questions