【问题标题】:Failed to add FK in rubyruby 中添加 FK 失败
【发布时间】:2022-01-17 08:58:54
【问题描述】:

我有报告课

class Report < ApplicationRecord
end

还有2个派生类Coachingreport和MedicalReport

class MedicalReport < Report
end

class CoachingReport < Report
end

还有播放器类

class Player < ApplicationRecord
end

我想创建一对多的关系,以便报告表将保存玩家 ID。但是,当我向 Report 类表添加关系时,创建的表单子类没有它们的列,只有 Report 类的列。但是当我专门为每个子类添加关系时,创建的表除了 player_id 之外的所有列。

【问题讨论】:

  • “没有他们的栏目”是什么意思?这些对象继承自 Report 并将存储在“reports”表中,一般来说,会在该表中添加一个 type 列,这将被称为单表继承 (STI) Docs。如果这些对象打算由单独的表支持,那么您将需要重新设计应用程序以支持这一点。你如何处理这取决于你想要的结果,不能从手头的问题中推断出来。

标签: ruby-on-rails ruby


【解决方案1】:

您的类需要声明关系,否则这些都不起作用。

class Report < ApplicationRecord
  belongs_to :player
end

class Player < ApplicationRecord
  has_many :reports
end

如果迁移工作正常,您应该有一个报告表和一个玩家表,其中报告表有一个player_id

报告子类仍将使用报告表。报告表需要一个type 字段来区分它们。 Reference.

【讨论】:

  • 感谢您的回答,我之前尝试过这样做,但是正如我提到的那样,MedicalReport 和 CoachingReport 的列不是从 Report 继承的列中创建的
  • 您认为创建关系和迁移的顺序会影响这件事吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
相关资源
最近更新 更多