如何使用 Devise 和 STI 将自定义字段添加到 Rails 中的用户类型?

How to add custom fields to user types in Rails with Devise and STI?

我正在尝试根据下图定义模型

我在尝试为“教师”类型生成迁移时出现问题,如果我无法创建迁移,我该如何向我的每个用户类型添加自定义字段(如薪水),因为它们不是table 就这样。

我已经使用 Devise for User 创建了一个模型,但我找不到此类案例的文档或相关示例以及用户类型的自定义字段。

STI代表单table继承。这意味着当您想向其中一个子类型添加一列时,您需要将该列添加到超类 table.

在您的示例中,当您需要 Teacher#salary 属性时,您需要将该 salary 列添加到 users table.

这意味着您需要像这样进行迁移:

class AddSalaryToUsers < ActiveRecord::Migration[6.1]
  def change
    add_column :users, :salary, :decimal, precision: 8, scale: 2
  end
end

您可能想在 Rails API docs and follow the link to Martin Fowler: Single Table Inheritance 中阅读有关 STI 的内容。