【问题标题】:Rails STi with 1 to 1 association具有 1 对 1 关联的 Rails STi
【发布时间】:2019-03-03 15:33:47
【问题描述】:

我有 2 个现有模型,我想创建一个 1 对 1 关联。我唯一的问题是这两个模型继承自同一个父类

class Model < ActiveRecord::Base

class Student < Model
  #has one :info


class Info < Model
  #belongs to :student

如何为此创建迁移?

【问题讨论】:

  • 这看起来可能像XY Problem。我同意@lacostenycoder 的观点,Model 似乎是一个特殊的名称。而且,StudentInfo 在语义上相似并不完全明显(至少对我而言)——那么为什么要使用 STI?此外,您没有说明“问题”是什么。以及您正在尝试为创建迁移的确切内容。
  • 我们对您的模型和关系了解不够,无法给出一个好的答案。 1对1并不能说明全部。请提供更多详细信息。
  • 您能解释一下为什么需要 STI 吗?为什么要将studentsinfo 存储在同一个表中?

标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord


【解决方案1】:

来自https://edgeguides.rubyonrails.org/active_record_migrations.html

rails generate migration AddUserRefToProducts user:references

生成

class AddUserRefToProducts < ActiveRecord::Migration[5.0]
  def change
    add_reference :products, :user, foreign_key: true
  end
end

此迁移将创建一个 user_id 列和适当的索引。如需更多 add_reference 选项,请访问 API 文档。

所以在你的情况下:

rails generate migration AddStudentRefToInfo student:references

这将产生以下迁移:

class AddUserRefToProducts < ActiveRecord::Migration[5.0]
  def change
    add_reference :info, :student, foreign_key: true
  end
end

请注意,假设您的“信息”模型存储在名为“信息”的表中。它可能是“信息”。

【讨论】:

  • 您好,感谢您的回答。但我使用的是单表继承,即只有模型保存在数据库中。模型中只有一个类型字段,用于将其与学生或信息区分开来
  • 您的答案是尝试解决 cmets 中提到的 XY 问题,请参阅xyproblem.info,但我想我也是。
【解决方案2】:

为什么要使用 Model 作为模型名称?我认为您正在寻找的是多态关系https://guides.rubyonrails.org/association_basics.html#polymorphic-associations

但如果没有关于您的模型的更多信息,我们无法提供最佳答案。 你可能想看看this article on STI vs Polymorphic relations

【讨论】:

  • 链接到“关于 STI 与多态关系的文章”似乎不正确。
猜你喜欢
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2016-07-01
相关资源
最近更新 更多