如何在 Rails 中使用多态从另一个对象创建子对象
我有两个类,Tutor 和 Session,它们以多态关系共享相同的子类 Field。
当导师创建会话时,我希望标题自动从导师复制到会话(即,一个新条目将添加到“字段”表中)。例如,
t = Tutor
Session.fields.build_from_tutor(t.fields)
我只是编写了 build_from_tutor 方法。有Rails/Ruby 方法可以做到这一点吗?
谢谢。
I have two classes, Tutor
and Session
which share the same child class Field
in polymorphic relationship.
When a tutor create a session, I would like to have the title to be automatically copied from Tutor to Session (i.e., a new entry will be added to 'Field' table). For example,
t = Tutor
Session.fields.build_from_tutor(t.fields)
I just make up build_from_tutor method. Is there a Rails/Ruby way to do this?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望相同的条目作为两个类的子项存在,那么这不是多态的;这只是混乱的继承。一个
Tutor has_many :sessions
和一个Session has_many :fields
,因此一个Tutor has_many :fields, :through => :sessions
,或者,Tutor has_many Sessions, :as => :fieldable
、一个Session has_many :fields, :as :feildable
和一个Field own_to :fieldable, :polymorphic => true
,但这会阻止 Tutor 和 Session 共享字段。所以你需要弄清楚这一点。然后你就可以找到一个理智的建造者。但不管怎样,你永远无法标准化你的数据模型。即使对于 Rails 应用程序,您也应该将 3NF 作为最低标准,恕我直言。
If you want the same entries to exist as the children of two classes, that's not polymorphic; that's just confused inheritance. Either a
Tutor has_many :sessions
, and aSession has_many :fields
, and thus aTutor has_many :fields, :through => :sessions
, or alternately, aTutor has_many Sessions, :as => :fieldable
, aSession has_many :fields, :as :feildable
, and aField belongs_to :fieldable, :polymorphic => true
, but that would preclude Tutor and Session ever sharing a field.So you need to figure that out. Then you can work out a sane builder. But yhe way you have it, you'll never be able to normalize your data model. Even for a Rails application, you should hold yourself to 3NF as a minimum standard, IMHO.