STI lưu nhiều subclass khác nhau vào một bảng DB dùng cột type để phân biệt.
ruby
# Migration
create_table :vehicles do |t|
t.string :type # STI column
t.string :name
t.integer :seats
t.integer :cargo_capacity # chỉ dùng cho Truck
end
# Models
class Vehicle < ApplicationRecord; end
class Car < Vehicle; end
class Truck < Vehicle; end
class Motorcycle < Vehicle; end
Car.create!(name: "Toyota") # type="Car"
Vehicle.all # trả về Car, Truck, Motorcycle cùng lúcDùng khi: các subclass có phần lớn attribute giống nhau, chỉ khác behavior.
Không dùng khi: subclass có nhiều attribute riêng → bảng sẽ rỗng (sparse columns), khó maintain. Thay bằng polymorphic association hoặc separate tables.
STI stores multiple subclasses in one DB table using a type column to distinguish them.
ruby
# Migration
create_table :vehicles do |t|
t.string :type # STI discriminator column
t.string :name
t.integer :seats
t.integer :cargo_capacity # only used by Truck
end
# Models
class Vehicle < ApplicationRecord; end
class Car < Vehicle; end
class Truck < Vehicle; end
class Motorcycle < Vehicle; end
Car.create!(name: "Toyota") # type="Car"
Vehicle.all # returns Cars, Trucks, Motorcycles togetherUse when: subclasses share most attributes and differ mainly in behavior.
Avoid when: subclasses have many unique attributes → table becomes sparse (many null columns), hard to maintain. Prefer polymorphic associations or separate tables instead.