Notes to self

Subclassing STI models in Rails

Here’s a short tip on opting out a specific model from Single Table Inheritance (STI).

Imagine a Vehicle model which is implemented using STI and extented with a type parameter to Sedan and Wagon models:

# Superclass
class Vehicle < ApplicationRecord
  self.inheritance_column = :type
end

# STI model
class Sedan < Vehicle
end

# STI model
class Wagon < Vehicle
end

All of this is nice except we might want to also subclass the Vehicle model as usual without any STI magic.

To do that we simply set inheritance_column to type_disabled:

# Non-sti sublassing, will behave as Vehicle
class Product < Vehicle
  self.inheritance_column = :type_disabled
end
Check out my book
Interested in Ruby on Rails default testing stack? Take Minitest and fixtures for a spin with my latest book.

Get Test Driving Rails and make your tests faster and easier to maintain.

by Josef Strzibny
RSS