What is STI in Rails ?
Single Table Inheritance in Rails is a technique used to categorize a base model into multiple sub-classes OR groups without needing to create new tables in the database.
A normal use case would be to have multiple models with almost the same attributes, hence using STI we can use the DRY concept by not creating extra tables in the database.
To illustrate this in a simple example, let’s have a main model named as
Pet.rb which is the
base model in our case. This model will have an attribute named as
This informs Rails that we are using STI and want to store all the data of
Pets and its subclasses in the same table in the database. Hence, we can create multiple sub-classes like
Cat.rbetc which will inherit its properties from the
From the above, we can notice how Single Table Inheritance works as every new instance that we save in the database is stored in
petstable only utilizing the Object-Oriented Design.
I hope the above concept is explained in the simplest manner possible. Any suggestions are very well appreciated.