Overriding fundamental ActiveRecord methods (like destroy) whilst preserving callbacks

[tweetmeme]
OK, so you’ve decided that it’s a good idea for you to override one of the fundamental methods on one of your ActiveRecord models. But in doing so, you have discovered that all of a sudden your callbacks have stopped working.

The reason for this is when your class is loaded, ActiveRecord::Callbacks have already hooked in the callback methods around the relevant methods using alias_method_chain meaning that the once named destroy method is now called destroy_without_callbacks.

So, to actually override the destroy method, use the following code:

def destroy_without_callbacks
  unless new_record?
    # do your code here
  end
  freeze
end

Note that the implementations will differ for other methods e.g. create, so you should check the ActiveRecord base class to see what should be in there.

Advertisements

One Response to “Overriding fundamental ActiveRecord methods (like destroy) whilst preserving callbacks”

  1. Overriding fundamental ActiveRecord methods (like destroy) whilst preserving callbacks « Fringley's Blog Says:

    […] reading Overriding fundamental ActiveRecord methods (like destroy) whilst preserving callbacks on my old blog… Tags activerecord, callbacks, destory, rails, ruby Categories […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: