Read more

Rails: Use STI in Migration

Julian
December 01, 2022Software engineer at makandra GmbH

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

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot
Julian
December 01, 2022Software engineer at makandra GmbH
Posted by Julian to makandra dev (2022-12-01 08:53)