Not everyday that you would run into STI (Single Table Inheritance). I’ve been setting up shipping and billing addresses for my User model in the recent project I’m working on and STI provides a great solution. However, there’s a little trick that seem to be missed by many STI articles.

Setting up STI is easy. First, add a ‘type’ column to your model with migration. Then, inherit the parent class to the subclasses.

By default, the column name should be ‘type’, but it can also be anything you want. If you decided to not use ‘type’, you would need to add this line of code: self.inheritance_column = :your_column_name, in the parent class.

Easy enough, right? Now comes the tricky part. You CANNOT have the subclassess in the same file as the parent class. Otherwise you will encounter an uninitialized constant error.

The solution is simple:

For example, my parent class is Address, and the STI subclasses are: ShippingAddress, and BillingAddress. You would need to create separate files, according to naming conventions, in models folder for those subclasses, and put those empty subclasses in. So I would need a shipping_address.rb for my ShippingAddress sublcass and a billing_address.rb for my BillingAddress subclass.

Much thanks to this issue.