ActiveRecord::MTI

Active

Maps Rails model subclasses onto PostgreSQL’s native table inheritance.

Single-table inheritance puts every subclass in one wide table. ActiveRecord::MTI gives each subclass its own table, using the inheritance PostgreSQL already has.

Each model in a hierarchy lives in a table created with INHERITS (parent). Querying through the parent returns rows from every child, and MTI reads the tableoid system column to instantiate the right Ruby subclass, so no discriminator column is needed.

It adds an inherits: option to create_table that survives schema dumps, and MTI and STI can be mixed in one hierarchy. QuickCount counts through MTI hierarchies too.

Highlights

  • No type column: the row’s own table decides its class
  • inherits: in migrations, preserved in schema.rb
  • Mix MTI and STI in one hierarchy
  • The most-starred project in the org

In practice

create_table 'account/users', inherits: :accounts do |t|
  t.string :email
end

Account.all
# => [#<User ...>, #<Admin ...>, #<Developer ...>]

The repository is at 0.5.0 with Rails 5.2 through 8.1 support; the newest RubyGems release is older, so install from git for current Rails.

Looking for our apps?

upuppy and the rest of our commercial software, with support and contact, live at twilightcoders.com.