[英]Rails Active Model Inheritance
I think what I'm trying to accomplish is multi table inheritance but I'm not sure how to properly implement it. 我认为我想完成的是多表继承,但是我不确定如何正确实现它。
I want to start with a base class Device
that will contain all the common fields such as name and enabled. 我想从一个基类
Device
,它将包含所有通用字段,例如名称和启用。
class Device
# in app/models
# Fields
# String name
# boolean enabled
end
I then want to create abstract classes for the different device types such as Light
that inherits from Device
然后,我想为不同的设备类型(例如从
Device
继承的Light
创建抽象类。
class Light < ActiveRecord:Base
# in app/models
# Fields
# String type
include Device
def on
raise NotImplementedError
end
def off
raise NotImplementedError
end
end
I then will have classes for specific devices such as X10Light
and ZWaveLight
that will define the specifics for each device and implement the abstract methods. 然后,我将具有针对特定设备的类,例如
X10Light
和ZWaveLight
,它们将定义每个设备的细节并实现抽象方法。
class X10Light < Light
# in app/models
# Fields
# String serial_number
def on
# fully implemented on method
end
def off
# fully implemented off method
end
end
My goal would then be to use it like the following 我的目标是像下面这样使用它
light1 = X10Light.new
light1.serial_number = "x1"
light1.save
light2 = ZWaveLight.new
light2.serial_number = "z1"
light2.save
all_lights = Light.all
all_lights.each do |light|
light.off
end
I think the way I have things planned out this is possible, but I think have some of the implementation incorrect. 我认为以这种方式进行计划是可行的,但我认为某些实现不正确。 I'd appreciate any help ironing out the details on this.
感谢您为解决此问题提供的任何帮助。 Thanks!
谢谢!
You can use Single Table Inheritance, you will need to create a model Device
which will hold all your fields plus a reserved column named type
, where rails will store the class name of the concrete instance. 您可以使用“单表继承”,您需要创建一个模型
Device
,该Device
将容纳您的所有字段以及一个名为type
的保留列,其中rails将存储具体实例的类名。
rails g model Device type:string ... other fields (ie columns for device, light, x10light) ...
class Device < ActiveRecord:Base
...
end
class Light < Device
...
end
class X10Light < Light
...
end
The downside of using STI is that you end up with a table which has all the columns of the tree of your inheritance. 使用STI的缺点是您最终得到一个表,该表包含继承树的所有列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.