how to subclass active record to call a method on all save and destroy actions

I'm looking for a way to subclass active record (I'll refer to the
subclass I want to create as NewActiveRecord) so that I can call
different methods on a save or destroy action on all models which sub
class NewActiveRecord

I dont want to use before_save or any of the other regular call back
methods as I want to be able to use these call backs in the models
which subclass NewActiveRecord without having to call super everytime
I use them.

Anyone have any ideas about how I can do this?



Use ActiveRecord::Observer instead of ActiveRecord::Callbacks?

You probably want to set self.abstract_class = true.


Thanks for the observer link, they would work nicely but I need to be
able to stop a model from saving or destroying, if the additional
method i call returns false.

Basically what I'm trying to do is add some authentication methods
into all my active record models so that whenever a save or destroy,
and also a association is added the authentication method checks that
the user has privileges to do this.


Thanks, I've heard that using self.abstract_class = true will allow me
to sub class ActiveRecord, I need to know which single method in
ActiveRecord is best to override to add the authentication methods. Do
you know which would be best?, or could you point me in the direction
of some good resources on ActiveRecord



For extending ActiveRecord the fairly new "Pro ActiveRecord" book from
APress is pretty good.

I'm not sure I'd recommend it for an introduction/only reference to AR
(AWDR 2ed does a better job IMHO) but for advanced things like
extending AR, it's the best resource I've found as yet.

We don’t do that kinda stuff in the Ruby world.

We use modules instead, so we can “mix in” that behavior.

In lib/ar_extentions.rb

module MyActiveRecordExtentions

def save(*args)

if some_condition

super(*args) # do the original


return false # or do your own stuff



def destroy

return false



Then all I need to do is

class User < ActiveRecord::Base

include MyActiveRecordExtensions


If you really want to see how this works in action, take a look at the acts_as_paranoid plugin. It uses this technique to mark records as deleted instead of actually deleting them, by overriding the destroy method. It’s a good place to start learning about this kinda stuff.

Thanks to all those who responded

I'll have a look at acts_as_paranoid and see what the best way forward