我知道,通过多态关联,一个模型可以在一个关联上属于多个其他模型。我想知道单个关联的含义。
您对多态关联的定义是正确的。术语“单协会”的手段,我们可以使用的组合record type
和record id
服务多个belongs_to
关系。我知道这听起来和定义本身一样含糊。因此,我将使用Rails指南中描述的多态关联示例:
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
关系的模型的关系。在上面的例子中,当我们增加一个Picture
用于Employee
ID为3,记录在创建Picture
模型为:
#<Picture id: 1, url: "some_url", imageable_type: "Employee", imageable_id: 3....>
请注意imageable_type和imageable_id如何帮助我们确定该图片所属系统中的确切记录。对于Product
ID为3的图片,图片如下:
#<Picture id: 1, url: "some_url", imageable_type: "Product", imageable_id: 3....>
没有多态关联,我们将不得不添加2列,employee_id
并且product_id
必须belongs_to
与上述模型具有关联。想象一下一个场景,其中5-6个不同的模型可能有图片!
使用多态关联有什么优势?
它们有助于建立用于与共享资源(例如图片,评论等)进行交互的统一API。
轻松添加可以共享资源的新模型,而无需添加新列。这也有助于避免记录中有多个未使用的列
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句