Rails: Use STI in Migration

Posted . Visible to the public.

tl;dr

You should decouple migrations from models by embedding models into the migration Show archive.org snapshot . To use STI in this scenario you have to overwrite find_sti_class and sti_name.

Tip

When possible, try to avoid STI in migrations by disabling it.

Example

Warning

This is more for the sake of I want to do it but I know I shouldn't do it.

# Your models:
# Vehicle
# Vehicle::Car
# Vehicle::Bike

class MyMigration < ActiveRecord::Migration[6.1]
  class Vehicle < ActiveRecord::Base
    def self.find_sti_class(type_name)
      super(name)
    end
  end
  
  class Car < Vehicle
    def self.sti_name
      'Vehicle::Car'
    end
  end
  
  class Bike < Vehicle
    def self.sti_name
      'Vehicle::Bike'
    end
  end
  
  def change
    up_only do
      Vehcile.last.class # => MyMigration::Vehicle::Car
    end
  end
end

Info

Without overwriting find_sti_class and sti_name you will see an error like this:

ActiveRecord::SubclassNotFound: Invalid single-table inheritance type: Vehicle::Car is not a subclass of MyMigration::Vehicle

Julian
License
Source code in this card is licensed under the MIT License.
Posted by Julian to makandra dev (2022-12-01 07:53)