简体   繁体   English

Ruby on rails 多态关联

[英]Ruby on rails polymorphic associations

Is there a difference between the has_many , has_and_belongs_to_many and the polymorphic association. has_many 、 has_and_belongs_to_many 和多态关联之间有区别吗? Why should I use polymorphic association.为什么要使用多态关联。

has_many , has_and_belongs_to_many and the polymorphic associations are solutions to different problems. has_manyhas_and_belongs_to_many多态关联是不同问题的解决方案。

  • has_many means you have a parent object that has many other children. has_many意味着您有一个父对象,其中包含许多其他子对象。 While the children do only belong to that specific parent.而孩子们只属于那个特定的父母。
  • has_and_belongs_to_many means the objects are not structured in a hierarchical structure. has_and_belongs_to_many表示对象不是按层次结构构建的。 And that the objects on both sides can be connected to mutiple others.并且两侧的物体可以连接到多个其他物体。 A good example is probably a tagging system.一个很好的例子可能是标签系统。 A thing can be tagged with multiple tags.一个事物可以用多个标签进行标记。 But the tags do not only belong to one thing, they can be added to other things too.但是标签不仅属于一件事,它们也可以添加到其他事物上。
  • polymorphic associations are used when the association doesn't point to one specific other model.当关联不指向一个特定的其他模型时,使用polymorphic associations An example might be an Author model that has a created_work association, but it doesn't point to a decicated CreatedWork model.一个示例可能是具有created_work关联的Author模型,但它并不指向指定的CreatedWork模型。 But instead, it can return different things, like an instance of a Book , a Play an Article , or a simple Comment which are all different classes and have different database tables.但是,它可以返回不同的内容,例如Book的实例、 Play an Article或简单的Comment ,它们都是不同的类并具有不同的数据库表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM