Reputation: 2881
I have a bunch of models which currently extend ActiveRecord::Base.
For all these models, I want to extend the save!
method with some additional functionality. For example,
def save!
begin
super
rescue
# additional exception handling logic
end
end
What is the ideal way to do this in an OOP fashion?
I tried subclassing ActiveRecord (MyActiveRecord) and used the above code in the subclass. Then I used the subclass as the parent class for all my models. But then, ActiveRecord tries to find the table myapp_test.my_active_records.
Is there a more elegant way using modules which achieves the same thing?
Upvotes: 2
Views: 532
Reputation: 84114
If you mark a class as abstract:
class Foo < ActiveRecord::Base
self.abstract_class = true
end
then you can subclass from it and rails won't go looking for a foos table.
In this particular case I wouldn't overwrite save though - there's already a set of callbacks (around_save
, around_update
etc) that probably make more sense.
Even if you were to do it by overwriting the save method, it might make more sense to do it by putting your overwritten save method in a module and including that module in the classes that require it.
module MySave
def save!
super
rescue
...
end
end
class MyClass < AR::Base
include MySave
end
Upvotes: 1