skip to content

In Active Record, what does self.abstract_class = true change for a shared parent model compared with an STI base class?

level: middleimportance: should knowfreq 33%

answer

  1. no table for the parent
  2. each subclass names its own table
  3. NotImplementedError on new
  4. no type column involved
  5. validates :type to forbid the base

basics

~20 s

self.abstract_class = true takes the parent out of the table mapping: it has no table, cannot be instantiated, and each subclass gets its own table. An STI base owns one shared table that its subclasses write into with a type column.

solid answer

~40 s

An STI base such as `Vehicle` is a concrete model: it owns `vehicles`, and `Truck < Vehicle` writes into that table with `type = 'Truck'`. Setting `self.abstract_class = true` on `Vehicle` removes it from the mapping instead: `Vehicle.table_name` is `nil`, `Vehicle.new` raises `NotImplementedError`, and each subclass becomes its own base class with its own table, so `Truck` reads `trucks` and `Van` reads `vans`, with no `type` column. The parent then only shares code: associations, validations, scopes and methods declared on it are inherited by every subclass. The cost is that nothing lists all vehicles in one query. To keep STI but forbid plain `Vehicle` rows, the API docs recommend `validates :type, presence: true` rather than an abstract class.

code

ruby · 13 lines
ruby
class Vehicle < ApplicationRecord
  self.abstract_class = true
  belongs_to :depot
  validates :plate, presence: true
end

class Truck < Vehicle; end   # table: trucks
class Van < Vehicle; end     # table: vans

Vehicle.table_name   # => nil
Truck.table_name     # => "trucks"
Truck.base_class     # => Truck
Vehicle.new          # NotImplementedError: Vehicle is an abstract class and cannot be instantiated.

go deeper

for a junior

Recall that an abstract parent has no table and cannot be instantiated, and that each subclass then uses its own table.

for a middle

Explain how Active Record picks the base class and table by walking up to an abstract class, and how that differs from an STI base that owns the table.

for a senior

Choose between an abstract parent, STI and a concern by asking whether the subtypes are ever listed together and how much data they share.

for a principal

Judge when an inheritance hierarchy among models is worth having at all, versus shared modules and plain separate models.

## Two meanings of a parent model When one Active Record model inherits from another, Rails has to decide which table the child uses. The answer depends on one flag on the parent, `abstract_class`: - If the parent is **concrete** (the default), it owns a table and the child shares it: that is **single-table inheritance (STI)**, with the class name in the `type` column. - If the parent sets `self.abstract_class = true`, it owns **no table**, and each child maps to a table of its own. The familiar abstract class is the generated `ApplicationRecord`, which is why ordinary models each have their own table. The same flag can be set on any intermediate class. ## What abstract_class does For a fleet app with `class Vehicle < ApplicationRecord; self.abstract_class = true; end`: 1. `Vehicle.table_name` is `nil`; there is no `vehicles` table to read. 2. `Vehicle.new` raises `NotImplementedError` with the message that the class is abstract and cannot be instantiated. 3. `Truck < Vehicle` becomes its own **base class**: `Truck.base_class` is `Truck`, its table is `trucks`, and it adds no type filter. 4. Associations, validations, scopes, callbacks and methods declared on `Vehicle` are inherited by every subclass, which is the reason to have the parent at all. ## Abstract parent or STI base | Question | Abstract `Vehicle` | STI base `Vehicle` | |---|---|---| | Tables | `vans`, `trucks`, `e_bikes` | one `vehicles` | | `type` column | not used | holds the class name | | `Vehicle.new` | raises `NotImplementedError` | builds a plain `Vehicle` row | | Listing every vehicle | one query per table | `Vehicle.all` | | Subtype-only columns | in each table, can be NOT NULL | NULL on other rows | | Renaming a subclass | renames a table | rewrites stored type strings | So an abstract parent is the right tool when the subtypes share **code** but are never listed or paginated together. When the app needs a single feed of all vehicles, an abstract parent forces a query per table, which is the gap STI and delegated types each fill. ## Listing across an abstract parent The absence of a table has a direct consequence: `Vehicle.all` has nothing to select from, so a screen listing every vehicle at a depot has to be assembled another way. - Query each subclass and combine the arrays in Ruby, which breaks database-side ordering and pagination across types. - Iterate `Vehicle.descendants`, remembering that in development it lists only subclasses that have been loaded. - Back a read-only model with a database view that unions the subclass tables, which brings back one queryable relation at the price of a view to maintain. - Or change the mapping: STI or delegated types both give one table that can be ordered and paginated. ## Mixing the two The flag only affects the class that sets it. An abstract class can sit above an STI hierarchy: - `TrackedRecord < ApplicationRecord` with `self.abstract_class = true` holds shared auditing code. - `Vehicle < TrackedRecord` is concrete, so it becomes the base class and owns `vehicles`. - `Truck < Vehicle` is stored in `vehicles` with `type = 'Truck'`. Active Record finds the base class by walking up until it meets `ActiveRecord::Base` or an abstract class, so the abstract layer is skipped when deciding the table. ## Traps - **Do not use abstract_class to forbid plain base rows.** Marking an STI base abstract moves every subclass to its own table. The API documentation's recommendation for "no bare `Vehicle` records" is `validates :type, presence: true` on the base. - **Order matters.** Set the flag in the parent's class body, before subclasses are defined and before any table name is computed. - **A concern is the lighter alternative.** If all you share is behaviour and the classes need no common Active Record parent, a module included in each model avoids an extra class in the hierarchy. - **`primary_abstract_class` is a different job.** It also sets `abstract_class`, but it marks the one class that holds the application's primary database connection, a role the generated `ApplicationRecord` already claims; it is not for grouping fleet models.

  • How do you keep STI but make sure no plain Vehicle row is ever saved?
    Keep `Vehicle` concrete so `Truck` and `Van` stay in `vehicles`, and add `validates :type, presence: true` on `Vehicle`. Base-class rows have a NULL type, so they fail validation, while every subclass record has its class name written automatically.
  • Can an abstract class sit above an STI hierarchy?
    Yes. Active Record walks up the ancestry until it meets `ActiveRecord::Base` or an abstract class, and the first concrete class below that is the base class. So `Vehicle < TrackedRecord` with an abstract `TrackedRecord` still owns `vehicles`, and `Truck < Vehicle` is stored there with a type.

  • An abstract Vehicle parent stores all its subclasses in a vehicles table.
  • Setting abstract_class on an STI base keeps subclasses in the base table.
  • Vehicle.new on an abstract class returns an unsaved record that cannot be persisted.
  • abstract_class adds a type column to each subclass table.