ruby-on-rails – rails模型子类 – >多表继承或多态
发布时间:2020-12-16 19:39:48 所属栏目:百科 来源:网络整理
导读:这是我的设置,其次是我要完成的工作的解释. class Layer ActiveRecord::Base has_and_belongs_to_many :componentsendclass Component ActiveRecord::Base has_and_belongs_to_many :layers endclass ImageComponent Component # I want this table to inher
这是我的设置,其次是我要完成的工作的解释.
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中很好地实现模型子类化? 现在我有我的组件模型设置是多态的,使ImageComponent和VideoComponent各有has_one:component,as::componentable.这给我的代码增加了一层烦恼和丑陋: image_component = ImageComponent.create component = Component.create component.componentable = image_component layer.components << component 我想一个简单的方法来解释这是我想在层和组件之间实现一个habtm关系.我有多种类型的组件(即ImageComponent,VideoComponent),每个组件具有相同的基本结构,但与它们相关联的不同字段.有关这方面可以实现的任何建议?我觉得我缺少一些东西,因为我的代码感觉到黑客. 解决方法
在Rails中实现这一点的“官方”方式是使用单表继承.对ActiveRecord:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#class-ActiveRecord::Base-label-Single+table+inheritance内置了STI的支持
如果你想使用多表继承,你必须自己实现… (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |