STI can be considered where single table can be used to represent multiple models based on different type. The parent model inherits from ActiveRecord::Base. Other models inherit from parent model. Data store and accessed from same table for all STI models. Lets take an example of User model which have multiple user types(admin, guest, merchant). In the database schema, sub-models are indicated by a single type column. Adding a type column in a database migration let Rails know that we are planning to implement STI.
class User < ActiveRecord::Base
class Admin < User
class Merchant < User
class Guest < User
Query Admin model:
Admin.where(:status => "active")
It trigger following SQL code. ActiveRecord automatically fetch data from the users table where the type is admin.
SELECT "users".* FROM "users" WHERE "users"."type" IN ('admin') AND "users"."status" = 'active'
STI is useful for all models that save data to the same table and share some functionlaities. Additionally we can write methods in sub classes. STI allows to keep data in a single table while writing specialized functionality.
Schema of table :
class User < ActiveRecord::Migration
create_table :users do |t|
After the schema is set up, the next step is to set up models and inheritance.
STI should be used carefully and only when required. If sub-classes that you want to use for STI have many different data fields, then the field may contain null values. That is not a preferred approach and hard to scale over time. In such cases you may prefer separate models to maintain the tables and functionalities.