Rails ActiveRecord - inheriting from a base class with no table
I had similar problem, but I wanted also to change the way AR was setting table_name for my models, that for example MyProject model would have table name "MY_PROJECT".
I've achieved it by creating abstract AR class, as @FFrançois said, and with inherited method, where I'm changing table name, like this:
class MyModel < ActiveRecord::Base
self.abstract_class = true
def self.inherited(subclass)
subclass.table_name = subclass.name.underscore.upcase
end
end
class MyProject < MyModel
end
Now MyProject.table_name gives MY_PROJECT :)
What you want is an abstract class:
class Option < ActiveRecord::Base
self.abstract_class = true
end
class ColorOption < Option
...
end
class FabricOption < Option
...
end
Looks like a case for a module that you include.
module Option
def self.included(base)
base.has_many :products
end
# other instance methods
end
class ColorOption < ActiveRecord::Base
include Option
set_table_name '???' # unless ColorOption / FabricOption have same table -> move to Option module
#stuff...
end
class FabricOption < Option
include Option
set_table_name '???' # unless ColorOption / FabricOption have same table -> move to Option module
#stuff...
end
More info: http://mediumexposure.com/multiple-table-inheritance-active-record/