Single table inheritance is not really all that intuitive – especially at first glance. To break down the concept as simply as possible seems to be the best way to get a greater grasp on the idea. It is, however, relatively standard when talking about STI to bring up ideas like ‘followers’ or ‘blocked connections.’ These are usually real world applications for STI’s, but they can be a bit hard to understand when first looking at the concept as a whole. This small post will be an over view, done in simple terms, to try and convey the CONCEPT of single table inheritance.
What is single table inheritance?
Single Table Inheritance is basically a way to add inheritance to your models. EXAMPLE: Lets say that you have a team_member model. The team members (assuming we are talking about something like football) can have a few different types: quarterbacks, tight ends, running backs, dbs, ect – but let’s not get ahead of ourselves. For this example, lets just keep it simple and say that you have defensive and offensive players. Both are team members, but they are different types of team member.
Both types of players share many of the same attributes. They all have numbers, positions, ages, salaries, ect. So, being that each player has so much in common, but they inherently have different behavior, this might be a good place to use STI. This will make your code a lot dryer by making it to where you don’t have to repeat a lot of the same columns in separate tables.
So, here is how the STI would work. You can keep the team_member model and subclass it with your separate types of team members: Offensive and Defensive. If you add a type column to the team_members table, active record automatically identifies the sub-models. Simple. Well, not really. You can go a lot deeper with STI’s – to the point of overusing them. That problem, however, only comes when you understand what they do. If you want to know more about STI, I’d check out some documentation. I’ll also link a pretty good tutorial I found below the article.
The main thing is to not get frustrated with it at first. STI is a notoriously confusing concept at first glance. Like with anything, however, practice makes being ok at it. 🙂 Happy coding.