【问题标题】:Polymorphic association with id and type in separate tables在单独的表中与 id 和类型的多态关联
【发布时间】:2020-02-17 11:07:23
【问题描述】:

我的应用程序中有一个类似于这样的自定义字段的多态关系:

class CustomFieldValue < ApplicationRecord
  belongs_to :custom_field_type
  belongs_to :custom_field_valuable, polymorphic: true
end
class CustomFieldType < ApplicationRecord
  has_many :custom_field_values
end

custom_field_type 表基本上包含有关字段类型(选择、复选框等)的一些详细信息,以及自定义字段所属模型的“model_type”列。

custom_field_value 表具有预期的多态列“custom_field_valuable_type”和“custom_field_valuable_id”,它们工作正常,但看到 custom_field_value 属于已经存储了 model_type 的 custom_field_type,我想知道是否有一种方法可以取消 custom_field_valuable_type ?

我已经尝试用

重新定义“custom_field_valuable_type”
def custom_field_valuabkle_type
  self.custom_field_type.model_type
end

但这不起作用,因为没有要查询的列。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    我想知道是否有办法消除 custom_field_valuable_type?

    否。 多态关联期望 association_name_type 列存在于具有关联的表上。 AFAIK 无法将类型列放在另一个表中,并且确实过于复杂。

    多态关联已经是解决对象关系阻抗不匹配问题的一个巧妙的解决方案,而且您从说外键由两列构造到外键由不同表上的列构造!这并没有改善任何东西,只会增加不匹配。

    您的方法不起作用,因为联接查询是在数据库中完成的,并且不调用您的 getter 方法。

    我认为您还混淆了两个完全不同的概念。您所做的只是实体属性值 (EAV) 模式的一种变体。您的 CustomFieldType 为设置提供的是属性的规范化 - 这样您就不会使用每个值复制属性的定义。这与链接 Value -> Entity 无关。

    【讨论】:

    • 也就是说,除非您有大量带有自定义字段的类,或者您正在编写库代码,否则您可能要考虑不使用多态关联,而每个类只使用一个(值)表。急切加载多态关联存在一些相当大的问题,这对于 EAV 来说将是非常有问题的。
    猜你喜欢
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多