In a Rails fleet app modelling vans, trucks and e-bikes, when does STI become sparse and brittle, and what does delegated_type change?
answer
- NULL columns for every other subtype
- no per-subtype NOT NULL
- shared columns stay on the delegator
- polymorphic belongs_to under the hood
- types: generates scopes and predicates
basics
~20 sSTI turns sparse and brittle once subtypes carry many columns of their own: those columns sit NULL on every other row and cannot be NOT NULL. delegated_type keeps shared columns on vehicles and moves each subtype's columns to its own table.
solid answer
~40 sSTI suits subtypes that share almost every column. Once trucks need `payload_tonnes` and `axle_count`, vans `cargo_volume_m3` and e-bikes `battery_kwh`, the `vehicles` table fills with columns that are NULL on most rows, none of them can be declared NOT NULL, every subtype field alters a hot table, and stored class names make renames data migrations. `delegated_type :vehicleable, types: %w[Van Truck EBike]` keeps one `vehicles` table for shared columns plus `vehicleable_type` and `vehicleable_id`, and gives each subtype its own table. It is a polymorphic `belongs_to` plus helpers: `Vehicle.trucks`, `vehicle.truck?`, `vehicle.truck`, `vehicleable_name`. The price is two rows per vehicle and an extra query to read subtype columns.
code
ruby · 22 lines# vehicles: id, plate, depot_id, status, vehicleable_type, vehicleable_id
class Vehicle < ApplicationRecord
belongs_to :depot
delegated_type :vehicleable, types: %w[Van Truck EBike], dependent: :destroy
delegate :capacity_label, to: :vehicleable
end
module Vehicleable
extend ActiveSupport::Concern
included { has_one :vehicle, as: :vehicleable, touch: true }
end
class Truck < ApplicationRecord # trucks: id, payload_tonnes, axle_count
include Vehicleable
def capacity_label = "#{payload_tonnes} t"
end
vehicle = Vehicle.create!(vehicleable: Truck.new(payload_tonnes: 18, axle_count: 3),
plate: "KX-204", depot: depot)
vehicle.truck? # => true
vehicle.van # => nil
Vehicle.e_bikes.count # WHERE vehicleable_type = 'EBike'go deeper
Recall that STI keeps all subtypes in one table with a type column, while delegated types split shared and subtype-specific columns across tables.
Explain what delegated_type generates: a polymorphic belongs_to, scopes such as Vehicle.trucks, predicates like truck?, readers like truck, and build_vehicleable.
Argue the switch from evidence: sparse columns, missing NOT NULL guarantees and hot-table migrations under STI, against two rows, extra queries and no foreign key under delegated types.
Treat the choice as a data-model bet: STI optimises for behaviour-heavy subtypes with shared data, delegated types for data-heavy subtypes listed together in one feed.
## Where STI starts to hurt **Single-table inheritance (STI)** stores every subtype in one table and records the class name in a `type` column. It is a good fit while the subtypes share nearly all of their columns. In a fleet-management app that holds for plate, depot and status, but not for the rest: trucks need `payload_tonnes` and `axle_count`, vans `cargo_volume_m3`, e-bikes `battery_kwh` and `charge_cycles`. Under STI, all of them land in `vehicles`: - **Sparse rows.** Every subtype-only column is NULL on the rows of every other subtype, and the table gains a column for each new subtype field. - **Weak constraints.** `payload_tonnes` cannot be declared NOT NULL because van and e-bike rows must leave it empty, so integrity falls back to model validations or a CHECK constraint written around `type`. - **Hot-table migrations.** Adding an e-bike field alters the one table that every vehicle query reads. - **Leaky models.** Columns define attribute methods on the whole table's model, so a `Van` answers `payload_tonnes` too. - **Stored class names.** The `type` column holds Ruby constant names, so renaming or namespacing a class needs a data migration. ## What delegated_type does **Delegated types** keep a concrete "superclass" table for what is shared and give each subtype its own table. `Vehicle` stays a real model with `plate`, `depot_id`, `status`, `vehicleable_type` and `vehicleable_id`; `Van`, `Truck` and `EBike` are separate models with only their own columns. The declaration is `delegated_type :vehicleable, types: %w[Van Truck EBike], dependent: :destroy`. Under the hood `delegated_type` calls `belongs_to :vehicleable, polymorphic: true` with the remaining options, so `dependent:` and `optional:` pass straight through and the link is required by default. Then it defines helpers from `types:`: | Generated method | Returns | |---|---| | `Vehicle.vehicleable_types` | `["Van", "Truck", "EBike"]` | | `Vehicle.trucks` | `Vehicle.where(vehicleable_type: "Truck")` | | `vehicle.truck?` | true when `vehicleable_type == "Truck"` | | `vehicle.truck` | the `Truck` record when it is one, otherwise `nil` | | `vehicle.truck_id` | `vehicleable_id` when it is a truck, otherwise `nil` | | `vehicle.vehicleable_name` | `"truck"`, `"van"` or `"e_bike"` | | `vehicle.build_vehicleable` | a new instance of the class named in `vehicleable_type` | The subtype side is usually a concern that each subtype includes: `has_one :vehicle, as: :vehicleable, touch: true`. ## Creating and querying 1. Create both rows at once: `Vehicle.create!(vehicleable: Truck.new(payload_tonnes: 18), plate: "KX-204", depot: depot)`. 2. List across types from one table: `depot.vehicles.order(:plate).limit(50)` paginates trucks, vans and e-bikes together, as STI would. 3. Filter by a subtype's own column through the subtype: `Truck.joins(:vehicle).where(payload_tonnes: 10.., vehicle: { depot_id: depot.id })`. 4. Share behaviour by delegation rather than case statements: `delegate :capacity_label, to: :vehicleable`, with each subtype defining `capacity_label` its own way. ## What it costs - **Two rows per vehicle**, and reading a subtype column means loading `vehicleable`, one more query per subtype when a list is preloaded. - **`types:` validates nothing.** It drives the helpers only; a stray `vehicleable_type` is not rejected by the declaration. - **No inheritance.** `Truck` is not a `Vehicle` in Ruby; shared columns are reached through `truck.vehicle`. - **No database foreign key on `vehicleable_id`**, because it points at a different table per row. ## Moving an existing STI table Switching a live fleet from STI to delegated types is an expand-and-contract migration rather than one step: 1. Create `vans`, `trucks` and `e_bikes` with their own columns, and add `vehicleable_type` and `vehicleable_id` to `vehicles`. 2. Backfill: for each vehicle row, insert one subtype row carrying its subtype-only values, and point `vehicleable_type` and `vehicleable_id` at it. 3. Switch the models: subtypes stop inheriting from `Vehicle`, include the shared concern, and `Vehicle` declares `delegated_type` and sets `self.inheritance_column = nil` while the old `type` column still exists. 4. Once nothing reads them, drop `type` and the subtype-only columns from `vehicles` in a later release. ## Choosing | Concern | STI | delegated_type | |---|---|---| | Rows per vehicle | one | two | | Subtype-only columns | NULL on other rows | in the subtype's table | | NOT NULL per subtype | not possible | ordinary column constraint | | Listing across types | one table | one table | | Reading subtype fields | already loaded | extra query | Pick STI while subtypes differ in behaviour more than in data; reach for `delegated_type` when each subtype brings a set of columns of its own.
- How do you query trucks by payload together with a vehicle column such as depot?Start from the subtype and join the delegator: `Truck.joins(:vehicle).where(payload_tonnes: 10.., vehicle: { depot_id: depot.id })`. A scope on the shared concern, such as `scope :with_vehicle, ->(attrs) { joins(:vehicle).where(vehicle: attrs) }`, gives every subtype the same shortcut.
- Why does vehicle.build_vehicleable work when a polymorphic belongs_to normally has no build_ method?A plain polymorphic `belongs_to` defines no constructors, because the target class is unknown. `delegated_type` adds `build_vehicleable`, which instantiates `vehicleable_class`, the constant named in `vehicleable_type`. So the type must be set first, as it is when a form submits `vehicleable_type`.
- Does types: stop a record from storing an unlisted class in vehicleable_type?No. `types:` only drives the generated scopes, predicates and readers. If the column must stay within the list, add a validation on `vehicleable_type` yourself; otherwise `vehicleable_class` constantizes whatever is stored.
STI is one paper form with boxes for every kind of vehicle, most left blank on each copy. delegated_type is a cover sheet holding what every vehicle shares, with a kind-specific attachment stapled on; reading the attachment means fetching it.
- delegated_type makes Truck a Ruby subclass of Vehicle with its own trucks table.
- With STI you can declare a truck-only column NOT NULL in the shared table.
- types: in delegated_type validates that vehicleable_type is one of the listed classes.
- delegated_type reads a truck's own columns without any query beyond the vehicles row.
- STI is always wrong; every hierarchy should use delegated types.