我知道,通过多态关联,一个模型可以在单个关联上属于多个其他模型。我想知道单个关联的含义。
您对多态关联的定义是正确的。术语“单个关联”表示我们可以使用record type
和record 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_id
和imageable_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_id
和product_id
才能与上述模型具有belongs_to
关系。想象一个场景,其中5-6个不同的模型可能有图片!
使用多态关联有什么优势?
它们有助于建立用于与共享资源(如图片,评论等)进行交互的统一API
允许轻松添加可以共享资源的新模型,而无需添加新列。这也有助于避免记录中有多个未使用的列]]