[英]Rails ActiveRecord - inheriting from a base class with no table
What i'm looking to do is have a base class for some of my models that has some default activerecord behavior: 我想要做的是为我的一些模型设置一个基类,它具有一些默认的activerecord行为:
class Option < ActiveRecord::Base
has_many :products
def some_method
#stuff
end
#etc..etc..
end
class ColorOption < Option
#stuff...
end
class FabricOption < Option
#stuff...
end
However, I want ColorOption and FabricOption to each be in their own tables. 但是,我希望每个ColorOption和FabricOption都在他们自己的表中。 I do NOT want to use STI or have a table for the base class "Option".
我不想使用STI或为基类“Option”设置表。 The only way I've gotten this to work is with some non-inheritance metaprogramming magic.
我实现这一点的唯一方法是使用一些非继承元编程魔法。 But I wondered if there was a way to tell AR that the base class does not need a table.
但我想知道是否有办法告诉AR基类不需要表。 Its just there for extra behavior, and to put the other subclasses in their own table as usual.
它只是用于额外行为,并像往常一样将其他子类放在自己的表中。
Thanks, Craig 谢谢,克雷格
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/ 更多信息: http : //mediumexposure.com/multiple-table-inheritance-active-record/
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". 我有类似的问题,但我也想改变AR为我的模型设置table_name的方式,例如MyProject模型将具有表名“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: 我已经通过创建抽象AR类来实现它,正如@FFrançois所说,并且使用继承方法,我正在更改表名,如下所示:
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 :) 现在MyProject.table_name给出MY_PROJECT :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.