rails model subclassing - >多表继承或多态

Mic*_*ick 12 ruby-on-rails ruby-on-rails-3

这是我的设置,然后解释我想要完成的任务.

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
Run Code Online (Sandbox Code Playgroud)

我希望能做什么:

layer.components << ImageComponent.create
layer.components << VideoComponent.create
Run Code Online (Sandbox Code Playgroud)

在实践中,我意识到ImageComponent并且VideoComponent实际上必须继承ActiveRecord::Base.有没有办法在Rails中很好地实现模型子类化?

现在,我有我的Component模型设置是polymorphic这样ImageComponentVideoComponent每个has_one :component, as: :componentable.这为我的代码增加了一层烦恼和丑陋:

image_component = ImageComponent.create
component = Component.create
component.componentable = image_component
layer.components << component
Run Code Online (Sandbox Code Playgroud)

我想解释这个问题的一个简单方法就是我想在层和组件之间实现一个habtm关系.我有多种类型的组件(即ImageComponent,VideoComponent),每种组件都具有相同的基本结构,但与它们相关联的字段不同.有关如何实现这一目标的任何建议?我觉得我错过了一些东西,因为我的代码感觉很乱.

sev*_*rin 10

在Rails中实现这一目标的"官方"方法是使用单表继承.ActiveRecord内置了对STI的支持:http://api.rubyonrails.org/classes/ActiveRecord/Base.html#class-ActiveRecord:: Base- label-Single+table+ inheritance

如果你想使用多表继承,你必须自己实现它...

  • 虽然可以访问字段,但每个子类可以具有不同的验证.因此,对于`VideoComponent`,您可以明确指定某些字段应为空白.但我可以想象`ImageComponent`和'VideComponent'之间可能存在很多重叠,因此在这种情况下STI似乎是最好的解决方案.如果你真的想要干掉你的数据模型,可以使用`Properties`表,其中每个组件都有`has_many:properties`.HTH. (3认同)
  • 谢谢.这是我最初的实现,但它感觉非常混乱,所有子类都可以使用子类特定的字段.即如果我想仅向ImageComponent添加一个字段,它也可用于VideoComponent.叹. (2认同)