skip to content

In Active Record single-table inheritance, what does the type column store, and how does it shape queries and loaded objects?

level: middleimportance: must knowfreq 48%

answer

  1. one table, class name per row
  2. inheritance_column defaults to "type"
  3. subclass relation adds a type filter
  4. base class query has no filter
  5. rows load as the class they name

basics

~20 s

Active Record STI keeps every subclass in the parent's table and writes the class name into the type column. Subclass queries add a type filter, and each loaded row is instantiated as the class its type names.

solid answer

~40 s

With STI, `Van`, `Truck` and `EBike` inherit from `Vehicle` and all live in the `vehicles` table. Active Record writes the class name into the column named by `inheritance_column`, which defaults to `"type"`, so `Truck.create!` stores `type = 'Truck'` without being told. A subclass relation filters on that column: `Truck.all` adds `WHERE vehicles.type = 'Truck'` (an `IN` list once loaded subclasses of `Truck` exist), so `Truck.find(van_id)` raises `ActiveRecord::RecordNotFound`. The base class adds no filter, and each row comes back as the class its `type` names, so `Vehicle.all` returns a mix of vans, trucks and e-bikes. `Vehicle.new(type: "Truck")` even returns a `Truck`, after checking the name belongs to the hierarchy. Rows of the base class itself keep `type` NULL.

code

ruby · 20 lines
ruby
# vehicles: id, type, plate, depot_id, payload_tonnes, battery_kwh, ...
class Vehicle < ApplicationRecord
  belongs_to :depot
end

class Van < Vehicle; end
class EBike < Vehicle; end
class Truck < Vehicle
  validates :payload_tonnes, presence: true
end

Truck.create!(plate: "KX-204", depot: depot, payload_tonnes: 18)
# INSERT INTO "vehicles" ("type", "plate", ...) VALUES ('Truck', 'KX-204', ...)

Truck.where(depot: depot).count
# SELECT COUNT(*) FROM "vehicles"
#   WHERE "vehicles"."type" = 'Truck' AND "vehicles"."depot_id" = 7

Vehicle.find(42).class            # => Truck, read from the type column
Vehicle.new(type: "EBike").class  # => EBike

go deeper

for a junior

Recall the shape: one table, a type column with the class name, subclasses that inherit from the base model and query only their own rows.

for a middle

Explain the mechanics: inheritance_column and its default, the type filter on subclass relations, base-class dispatch on load, and why Truck.find of a van id raises RecordNotFound.

for a senior

Show you have run STI in production: unloaded descendants in development, class renames as data migrations, and legacy type columns that need inheritance_column set to nil.

for a principal

Frame STI as a schema commitment: stored class names couple data to code, so weigh it against delegated types or separate tables before a hierarchy grows.

## What single-table inheritance means in Active Record **Single-table inheritance (STI)** lets several Ruby classes share one database table. In a fleet-management app, `Van`, `Truck` and `EBike` can all inherit from `Vehicle`, and every one of them is stored in the `vehicles` table. Active Record tells the rows apart by writing the class name into a dedicated column. Nothing has to be declared beyond the class hierarchy: a model whose table has a column named `type` and whose class inherits from another concrete model is using STI. - The parent (`Vehicle`) is the **base class**: it inherits from `ApplicationRecord` and owns the table. - Each subclass (`class Truck < Vehicle; end`) has no table of its own; its `table_name` is `vehicles`. - Columns for every subclass live in the one table, so a truck-only column such as `payload_tonnes` is simply NULL on van and e-bike rows. ## The inheritance column The column that holds the class name is set by the `inheritance_column` class attribute, whose default is `"type"`. Two settings change it: 1. `self.inheritance_column = "kind"` points STI at a differently named column, which helps on a legacy schema. 2. `self.inheritance_column = nil` switches STI off, so a `type` column becomes an ordinary attribute. When you build a subclass record, Active Record writes the value itself: `Truck.new` already has `type` set to `"Truck"`, which is why a fresh subclass record reports itself as changed before you assign anything. The value written is `sti_name`, the full constant name (`"Fleet::Truck"` for a namespaced class), because `store_full_sti_class` defaults to `true`. A record of the base class itself leaves `type` NULL. The base class's `new` reads the column as well: `Vehicle.new(type: "Truck")` returns a `Truck`. The name is checked first, so a value that does not resolve to `Vehicle` or one of its subclasses raises `ActiveRecord::SubclassNotFound` instead of building a record. ## What SQL each class runs | Call | Type filter added | Objects returned | |---|---|---| | `Vehicle.all` | none | a mix of `Van`, `Truck`, `EBike` (and `Vehicle` for NULL rows) | | `Truck.all` | `WHERE vehicles.type = 'Truck'` | `Truck` objects | | `Truck.all` once `HeavyTruck < Truck` is loaded | `type IN ('Truck', 'HeavyTruck')` | `Truck` and `HeavyTruck` objects | | `Truck.find(van_id)` | the same `Truck` filter | raises `ActiveRecord::RecordNotFound` | The filter is part of the default relation of every class below the base: Active Record lists the class's own `sti_name` plus those of its known descendants. One name renders as an equality, several as an `IN` list. The base class adds no condition, which is why `Vehicle.where(depot_id: 3)` returns every kind of vehicle at that depot. ## How a row becomes an object When rows come back, Active Record reads the inheritance column of each one and instantiates the class it names. So `Vehicle.find(42)` returns a `Truck` if row 42 says `Truck`, and the truck's own methods and validations are available on it. If a stored name cannot be resolved to a constant, loading raises `ActiveRecord::SubclassNotFound`, whose message suggests renaming the column or setting `inheritance_column` to `nil`; that is the usual symptom of a legacy table that happens to have a column called `type` holding something else. ## Rails-specific traps - **Lazy loading in development.** The descendant list in the filter holds only classes Ruby has loaded. The generated `config/environments/development.rb` sets `config.eager_load = false`, so `Truck.all` can leave out `HeavyTruck` rows until something references `HeavyTruck`. The autoloading guide's fixes are eager loading, or preloading the hierarchy's directory in a `to_prepare` block with `Rails.autoloaders.main.eager_load_dir`. - **Renaming a class is a data migration.** Rows store the class name, so renaming `EBike` or moving it into a namespace leaves old rows pointing at a name that no longer exists. - **Generating subclasses.** `bin/rails generate model Truck --parent=Vehicle` writes `class Truck < Vehicle` and skips the migration, because the table already exists; subclass-only columns still need a migration on `vehicles`. - **Behaviour per subclass is ordinary Ruby.** Validations, associations and methods declared on `Truck` apply to trucks only, while those on `Vehicle` apply to every row. - **Associations aimed at a subclass filter too.** `has_many :trucks` on `Depot` reads `vehicles`, matches `depot_id`, and adds the `Truck` type condition, because the association's scope starts from the `Truck` relation. `has_many :vehicles` on the same model returns every kind. - **Uniqueness and indexes are table-wide.** A unique index on `plate` covers vans, trucks and e-bikes together, since they share one table; that is usually what a fleet wants, but it is worth saying out loud when subtypes have separate numbering.

  • Why can Truck.all leave out HeavyTruck rows in development but not in production?
    The type filter lists `Truck` plus its descendants that Ruby has already loaded. The generated development config sets `config.eager_load = false`, so until `HeavyTruck` is autoloaded it is not a descendant and its rows drop out. Production eager loads, so the list is complete. The fix is to preload the hierarchy, for example `Rails.autoloaders.main.eager_load_dir` on its directory inside a `to_prepare` block.
  • A legacy table has a type column holding values like "diesel", and loading rows raises SubclassNotFound. What do you do?
    Active Record treats any `type` column as the STI column and tries to turn `"diesel"` into a class. Set `self.inheritance_column = nil` on the model so `type` becomes a plain attribute, or point `inheritance_column` at another column if the table really does use STI under a different name.
  • How do you add a new STI subclass with the generator?
    `bin/rails generate model EBike --parent=Vehicle` writes `class EBike < Vehicle` and creates no migration, because a custom parent without `--database` skips migration generation. Any e-bike-only columns, such as `battery_kwh`, are added to `vehicles` with a separate migration.

  • Each STI subclass such as Truck gets its own trucks table.
  • Truck.find(id) loads any vehicles row and casts it to a Truck.
  • You have to set the type column yourself on every Truck.create.
  • Vehicle.all returns only base rows whose type column is NULL.
  • Vehicle.new(type: "String") quietly builds a plain Vehicle and ignores the bad name.