DynamoDB Dynomite Single Table Inheritance

Important: These docs are for the outdated Jets 5 versions and below. For the latest Jets docs: docs.rubyonjets.com

Dynamoid supports STI, Single Table Inheritance. You can enable it like so:

class Vehicle < ApplicationItem
  enable_sti
end
class Bike < Vehicle
end
class Car < Vehicle
end

The table name of the subclasses Bike and Car is same as the Vehicle class.

Vehicle.table_name  # demo-dev_vehicles
Bike.table_name     # demo-dev_vehicles
Car.table_name      # demo-dev_vehicles

The default inheritance field is type and the class name is saved into that field.

Bike.create(color: "blue")
Car.create(color: "blue")
Bike.where(color: "blue").count    # 1
Car.where(color: "blue").count     # 1
Vehicle.where(color: "blue").count # 2

Querying is automatically scoped to the type field.

Car.where(color: "blue").count                  # 1
Vehicle.where(color: "blue", type: "Car").count # 1

Inheritance Field

You can change the inheritance field to use by passing it as a argument.

class Vehicle < ApplicationItem
  enable_sti :kind
end

Note: enable_sti and inheritance_field are aliases. So this also works:

class Vehicle < ApplicationItem
  inheritance_field :kind
end

Multiple Levels of Subclasses

Subclasses at additional levels will still be stored in the same type.

class ElectricCar < Car
end
ElectricCar.table_name  # demo-dev_vehicles

The table name is the first non-abstract class. If you need to make a base class that’s a subclass of ApplicationItem abstract, you can call the abstract! method.

Related Rails ActiveRecord Docs: