Learning Ruby on Rails

My adventures at the Flatiron School

Using Polymorphic Associations in Rails pt.1

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.

models/answer.rb
1
2
3
4
5
class Answer < ActiveRecord::Base

   has_many :comments, :as => :commentable

end

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

models/issue.rb
1
2
3
4
5
class Issue < ActiveRecord::Base

  has_many :comments, :as => :commentable

end

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.

models/comment.rb
1
2
3
4
5
class Comment < ActiveRecord::Base

  belongs_to :commentable, :polymorphic => true

end

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.