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.
Make yourself useful.