【问题标题】:Why is there a polymorphic relationship?为什么会有多态关系?
【发布时间】:2017-12-03 15:13:08
【问题描述】:

为什么会有多态关系?如果数据库表未规范化,为什么要使用这种多态关系?这是为了在数据库中保留更少的数据而设计的吗?我正在研究 2 天,但我没有找到一致的答案。你能帮帮我吗?

【问题讨论】:

    标签: ruby-on-rails database polymorphism associations


    【解决方案1】:

    当关系可以同时应用于多个模型时,使用多态关系。

    假设您有一个名为Profile 的模型,其中包含Teacher 和Student 的所有管理数据

    关系如下:

    Student has_one :profile
    Teacher has_one :profile
    Profile belongs_to :student
    Profile belongs_to :teacher
    

    现在假设您选择Profile 的第一条记录:

    @p = Profile.first
    

    你想得到这条记录的父级..这是一个问题,因为你不知道你是否必须做@p.student或@p.teacher

    那么多态关联可以证明是有用的,它在Profile 中添加了两个字段:父类的类和父类的id。它解决了知道它适用于哪个父母的问题。

    您只需要调用一个中间抽象模型(假设 Profileable 并不真正作为表存在于数据库中,但会导致不知道其类的父级)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-26
      • 2012-11-07
      • 2019-02-01
      • 2010-10-31
      • 2015-09-16
      • 2016-06-14
      • 1970-01-01
      • 2013-09-15
      相关资源
      最近更新 更多