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.
August 28, 2010 at 1:40 pm
[...] reading Overriding fundamental ActiveRecord methods (like destroy) whilst preserving callbacks on my old blog… Tags activerecord, callbacks, destory, rails, ruby Categories [...]