So we all know that rails' STI (single table inheritance) is icky because it leads to a cluttered data model and suboptimal database.
However PostgreSQL seems to handle inheritance quite beautifully!
Is there a way to get rails' nice clean STI API while utilizing Postgres inheritance instead of painfully wide tables and "type" columns?
Inheritance is when a class receives or inherits the attributes and behavior of another class. The class that is inheriting the behavior is called the subclass (or derived class) and the class it inherits from is called the superclass (or base class). Imagine several classes - Cat, Dog, Rabbit, and so on.
Inheritance in PostgreSQL allows you to create a child table based on another table, and the child table will include all of the columns in the parent table. Let's take a database that's used to store blueprints for different types of homes.
Single Table Inheritance (STI) models are defined as separate classes inheriting from one base class, but they aren't associated with separate tables — they share one database table. The table contains a type column that defines which subclass an object belongs to.
Inheritance is when a class inherits behavior from another class. The class that is inheriting behavior is called the subclass and the class it inherits from is called the superclass.
However PostgreSQL seems to handle inheritance quite beautifully!
Really? Did you take a close look at the small print in the manual? For example:
capitals
extends cities
. Your address
table wants to reference cities
. It can. But the no address with a capital
can be used.These two things are very important in anything beyond a small "Hello World" project. So I cannot imagine, that anything productive can be implemented using PostgreSQL inheritance.
In short - no there no nice clean STI API for what you are trying to accomplish as of right now.
I actually looked into that a about a year ago and came to a conclusion that it is not a good idea for several reasons:
Most IT problems really come down to this: Effort vs Benefit.
In your case you should ask yourself this question:
P.S.:
Also a quick tip on structuring STI in your app: If you find that you have a lot of models that use STI like a ProductCategory, CommentCategory, PhoneCategory, ClientCategory that all inherit from Cateogory - I tend to organize them in folders inside model directory. Then in application.rb just add a line: config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**/**}')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With