Single Table Inheritance In Rails

Huzefa S Biyawarwala
1 min readMay 15, 2021

--

STI Rails

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 type.

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 Dog.rb, Cat.rbetc which will inherit its properties from the Pet.rb .

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.

--

--

Huzefa S Biyawarwala

Ruby On Rails | MongoDB | ReactJS | AWS | Freelance Consultant