【问题标题】:Rails - Columns pointing to same tableRails - 指向同一个表的列
【发布时间】:2017-07-01 10:20:21
【问题描述】:

我有一个包含表 containersports 的数据库。

containers 表有两列 pol_idpod_id,它们都指向 ports 表。 ports 表有一个 id 列。

我曾尝试在迁移中使用belongs_to / references,但它没有提供这种灵活性。

另外,我对为此配置模型有点困惑。

【问题讨论】:

  • 在你的容器和端口模型中显示代码
  • 我想你只是想在你的 belongs_to 关联中指定 foreign_key。
  • 这是您的模型配置的一个很好的答案:stackoverflow.com/questions/25047920/…

标签: ruby-on-rails database model rails-activerecord


【解决方案1】:

您可以在创建迁移时使用foreign_key 选项来自定义外键:

t.references(:pol, foreign_key: { to_table: :ports })

在您的模型中,您需要告诉 ActiveRecord 关联指向哪个类:

class Container
  belongs_to :pol, class_name: "Port"
end

创建反向关联时还需要提供外键:

class Port
   has_many :containers_as_pol, class_name: "Container", foreign_key: "pol_id"
end

【讨论】:

  • 请注意,迁移中的 belongs_to 只是引用的别名,所以同样适用。
猜你喜欢
  • 2020-09-19
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多