【发布时间】:2012-11-08 20:11:00
【问题描述】:
这是我的设置,然后是我想要完成的解释。
class Layer < ActiveRecord::Base
has_and_belongs_to_many :components
end
class Component < ActiveRecord::Base
has_and_belongs_to_many :layers
end
class ImageComponent < Component
# I want this table to inherit from the Component table
# I should be able to add image-specific fields to this table
end
class VideoComponent < Component
# I want this table to inherit from the Component table
# I should be able to add video-specific fields to this table
end
我想做什么:
layer.components << ImageComponent.create
layer.components << VideoComponent.create
在实践中,我意识到ImageComponent 和VideoComponent 实际上必须从ActiveRecord::Base 继承。有什么方法可以很好地在 Rails 中实现模型子类化?
现在我的Component 模型设置为polymorphic,这样ImageComponent 和VideoComponent 每个has_one :component, as: :componentable。这给我的代码增加了一层烦恼和丑陋:
image_component = ImageComponent.create
component = Component.create
component.componentable = image_component
layer.components << component
我想一个简单的解释方法是我想在层和组件之间实现一个 habtm 关系。我有多种类型的组件(即 ImageComponent、VideoComponent),每个组件都具有相同的基本结构,但与之关联的字段不同。关于如何实现这一点的任何建议?我觉得我遗漏了一些东西,因为我的代码感觉很hackish。
【问题讨论】:
-
我认为继承本身应该可以工作(也就是说,
create应该是ImageComponent的一种方法)但是 AR 的东西不会,因为它对文件和表名以及就像基于类名一样。虽然我认为 Rails 的大部分魔法都可以被覆盖,但也许更好的方法是使用 mixin,而不是直接继承。 -
到底是什么问题? rails 实现模型子类化。这一切与多态性与多表继承有什么关系?
-
多态和多表继承是我想要做的两种方法,但对于我的情况,这两种方法都不是特别干燥。我想将多表继承与模型子类化结合起来。 AFAIK 你不能创建一个模型的子类来为子类提供一个新的表。我在上面示例中的子类无法实现自己的字段——它们被绑定到超类的字段。
标签: ruby-on-rails ruby-on-rails-3