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

422 Views Asked by At

I am trying to define the models based on the following diagram

UML diagram

My problem occurs when trying to generate a migration for the "Teacher" type, how can I add a custom field (like salary) to each of my user types if I can't create a migration because they are not a table as such.

I already have a model created with Devise for User, but I cannot find documentation or related examples for this type of case with custom fields for User types.

1

There are 1 best solutions below

0
spickermann On BEST ANSWER

STI stands for single table inheritence. This means when you want to add a column to one of the subtypes then you need to add that column to the superclasses table.

In your example, when you want a Teacher#salary attribute then you need to add that salary column to the users table.

This means you will need a have a migration like this:

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

You might want to read about STI in the Rails API docs and follow the link to Martin Fowler: Single Table Inheritance.