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
我希望能做什么:
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),每种组件都具有相同的基本结构,但与它们相关联的字段不同.有关如何实现这一目标的任何建议?我觉得我错过了一些东西,因为我的代码感觉很乱.
sev*_*rin 10
在Rails中实现这一目标的"官方"方法是使用单表继承.ActiveRecord内置了对STI的支持:http://api.rubyonrails.org/classes/ActiveRecord/Base.html#class-ActiveRecord:: Base- label-Single+table+ inheritance
如果你想使用多表继承,你必须自己实现它...
| 归档时间: | 
 | 
| 查看次数: | 9171 次 | 
| 最近记录: |