【发布时间】:2020-11-12 07:35:37
【问题描述】:
has_many 、 has_and_belongs_to_many 和多态关联之间有区别吗? 为什么要使用多态关联。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-5 associations polymorphic-associations
has_many 、 has_and_belongs_to_many 和多态关联之间有区别吗? 为什么要使用多态关联。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-5 associations polymorphic-associations
has_many、has_and_belongs_to_many 和 多态 关联是不同问题的解决方案。
has_many 表示您有一个父对象,该对象有许多其他子对象。而孩子确实只属于那个特定的父母。has_and_belongs_to_many 表示对象不是分层结构。并且两侧的对象可以连接到多个其他对象。一个很好的例子可能是标签系统。一个事物可以用多个标签进行标记。但是标签不仅属于一件事,还可以添加到其他事物上。polymorphic associations 在关联不指向一个特定的其他模型时使用。一个示例可能是具有created_work 关联的Author 模型,但它并不指向一个指定的CreatedWork 模型。但相反,它可以返回不同的内容,例如 Book、Play、Article 或简单的 Comment 的实例,它们都是不同的类并具有不同的数据库表。【讨论】: