Rails Polymorphic Associations

Clean up your database design with this cool feature

Photo by Julian Hochgesang on Unsplash

I’ve probably read this a million times before realizing how useful of a feature it was in Rails. https://guides.rubyonrails.org/association_basics.html#polymorphic-associations

Most people might be familiar with Single Table Inheritance (STI) where you use the same table for multiple subclasses that have the same structure. The way it works is you have a type column which stores the class name to tell you which kind of object that row refers to.

Polymorphic associations are somewhat similar because they use a type column but the use case is not for determining what data is stored within a table but how tables relate via foreign keys.

I forget where I read this but an easy way to remember table structure in rails relationships is that when a model belongs_to another, that means it has a foreign key to it. So when ModelA belongs_to :model_b , then it has a model_b_id on it.

Keeping in mind that above trick, what if a single ModelA instance belongs_to one of several other models? Like a Comment for example. Comments usually are associated with a single type, a Post or an Item or an Image… in that case you could potentially have a whole plethora of other_model_id columns that are going to be null most of the time.

That’s where polymorphic relationships help because the way it works is you have thetype column like in STI, and you also have a single foreign key column. By convention you use the -able suffix to help with naming. So if a comment can belong_to a Post or Item or Image, those other models are considered “commentable”

Looks like this:

Now you can say:

Hope that makes even just a little sense 🙂. Really I just wanted to draw attention to something that can be used to help others clean up a lot of messy associations, after it was recently brought to mine.