Single Table Inheritance vs Polymorphic Associations in Rails

These two things are sometimes confused because they both involve columns with the word type in. In fact they serve very different purposes.

Single Table Inheritance is when models share a database table but have different behaviour. For example, in your beekeeping newsletter application you might have a Subscription model which comes in two flavours: PaidBeeSubscription and FreeBeeSubscription. These are identical in all respects except the way they react to the method #price. There is a field on the Subscription class called type, which tells Rails which class to give you when you load that model.

A polymorphic association is when you have different models that need to have_many of the same thing. For example, you might have a Donkey class and a Tortoise class in your petting zoo application, and both of these things can have Pictures associated with them. Follow the Rails Guides to learn how it works, but the effect is that a Picture carries a relation to an imageable model which could be a Donkey or a Tortoise — Picture doesn’t care which. To help Picture know which model to give you when you request its imageable, it has a column called imageable_type, which records whether the associated model is a Donkey or a Tortoise or a Porpoise or whatever.

As you can see, these things are more or less totally unrelated. But people get them confused because they both have columns with the word type in, and those type columns both contain the names of Rails models.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s