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
Single Table Inheritance(STI) is a useful and sharp technique, and like any other high level instrument you should use it in an appropriate place. Let’s take a closer look with examples
For example you have a Blog, inside this blog you will have for sure such objects:
- User Avatar
- Comments Attachments
First thing that you should create is a table from which you will inherit:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Let’s see what will happens in terminal:
1 2 3 4 5 6 7 8
How does it work?
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)
So when you inherit from some table your child tables will insert class name in
This looks good, you create one table, make an abstraction and right now everything work nice.
When you will specify each uploader you could create different behavior and image size(I will not cover it in this post feel free to visit This link)
You could go to your boss and say they your are awesome :)
Where is the evil?
What will happens when you will create a User?
1 2 3 4 5 6 7 8 9
You should add
user_id to your asset table.
Oh, yes you also need a
Post, that will include
Images, and yes you have a
Comments, that attach to you
And in the end you will face this kind of scheme:
1 2 3 4 5 6 7 8 9 10
Half of your table will be filled with
Maybe someday you will decide to use your
CommentAttachment for attaching
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Right now your table will looks like a crap. And your project will became soo huge that you could not to refactoring well.
Use STI only when you totally sure that you will never change it. This post based on a true story.