谁能举例说明多态关联吗?

问题描述 投票:0回答:1

我知道,通过多态关联,一个模型可以在单个关联上属于多个其他模型。我想知道单个关联的含义。

activerecord ruby-on-rails-5 rails-activerecord
1个回答
0
投票

您对多态关联的定义是正确的。术语“单个关联”表示我们可以使用record typerecord id的组合来服务多个belongs_to关系。我知道这听起来和定义本身一样含糊。因此,我将使用Rails guide description of polymorphic associations

中提到的示例
class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

class Employee < ApplicationRecord
  has_many :pictures, as: :imageable
end

class Product < ApplicationRecord
  has_many :pictures, as: :imageable
end

[这里,picture模型是多态模型,它具有两列,imageable_idimageable_type。它使用这两列来建立与具有has_many :pictures, as: :imageable关系的any模型的关系。在上面的示例中,当我们为ID为3的Picture添加Employee时,会在Picture模型中创建一条记录,如下所示:

#<Picture id: 1, url: "some_url", imageable_type: "Employee", imageable_id: 3....>

请注意类型和ID如何帮助我们识别该图片所属系统中的确切记录。对于ID为3的Product,图片如下:

#<Picture id: 1, url: "some_url", imageable_type: "Product", imageable_id: 3....>

Without多态关联,我们必须添加2列employee_idproduct_id才能与上述模型具有belongs_to关系。想象一个场景,其中5-6个不同的模型可能有图片!

使用多态关联有什么优势?

  1. 它们有助于建立用于与共享资源(如图片,评论等)进行交互的统一API

  2. 允许轻松添加可以共享资源的新模型,而无需添加新列。这也有助于避免记录中有多个未使用的列]]

© www.soinside.com 2019 - 2024. All rights reserved.