Using Polymorphic Associations in Rails pt.1

Flatiron School / 15 November 2012

The following is a guest post by Brad Wheel and originally appeared on his blog. Brad is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here. Look out for part 2 soon!

I was working on a project yesterday with my group when we came across a problem. We have an Answer table, Issue table, and a Comment table. We wanted to be able to comment on both an answer and an issue, but didn’t know how to set up the associations in our models.Originally, we thought of creating separate models for AnswerComments and IssueComments, but after some discussion we decided it would be good practice to create a polymorphic association.

So, what are polymorphic associations? It is when a model belongs to more than one model without using more than one association. While we may only have two models that we want to comment on right now, this allows us the freedom in the future to comment on more things without setting up extra tables.

Here is my Answer class. An answer has_many :comments just like a regular has many/belongs to relationship, but here, we added a second parameter :as, which specifies the interface to map to.

Here is my Issue class, which is setup just like my Answer class.

My Comment class looks a little different because it belongs to both an Answer and an Issue. By telling Rails that a comment belongs_to :commentable, it is saying to look for the model type in commentable. The extra parameter :polymorphic just specifies that it is in fact a polymorphic relationship.
We’re going to stop here now that we have our models set up, but in pt. 2 we will look at how we set up our routes.
Setting Up a Staging Environment to Use OmniAuth Facebook Previous Post How to Close a Git Pull Request Next Post