DynamoDB Dynomite Single Table Inheritance

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

class Vehicle < ApplicationItem
class Bike < Vehicle
class Car < Vehicle

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

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

class Vehicle < ApplicationItem
  inheritance_field :kind

Multiple Levels of Subclasses

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

class ElectricCar < Car
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: