Rails Single Table Inheritance
Single table inheritance is as the name suggests it a way to add inheritance to your models.
Rails single table inheritance. 1 what is single table inheritance sti. If you ve ever created an application with more than one model you ve had to think about what type of relationships to use between those models. Single table inheritance is a way to emulate object oriented inheritance in a relational database when mapping from a database table to an object in an object oriented language a field in the database identifies what class in the hierarchy the object belongs to. To follow this tutorial you will need a working rails environment.
I would like to show some typical problems related to sti usage and propose different solutions and perhaps workarounds. What is single table inheritance. Sti is basically the idea of using a single table to reflect multiple models that inherit from a base model which itself inherits from activerecord base. All fields of all the classes are stored in the same table hence the name single table inheritance.
Ruby on rails 6 0 3 1. If you define any subclasses from your activerecord model objects then you should consider sti. One of the most common of them is the usage of sti single table inheritance. In short single table inheritance sti is a design pattern that allows a mapping of oop inheritance relationships to the database.
I ll be using rails 4 2 3 and sqlite as the database. In active record the class name is stored as the type in the table. Polymorphic associations in rails. I recently forked a promising project to implement multiple table inheritance and class inheritance in rails.
In the database schema sub models are indicated by a single type column. Single table inheritance sti in rails allows you to store ruby subclasses in the same database table. It is even considered best practice by some people for some use cases ymmv. Single table inheritance active record allows inheritance by storing the name of the class in a column that by default is named type can be changed by overwriting base inheritance column.
Generate a migration for it. Rails new sti demo first an empty user model. To implement sti we add a column called type of type. Find what works for you photo by sanwal deen on unsplash.
In brief single table inheritance in rails allows you to store multiple types of classes in the same table. I will use ruby 2 0 with rails 4 but you should be able to test the code using any version of ruby superior to 1 9 2 and at least rails 3.