May 22, 2013
In polymorphic associations, a model can fit into more than one model, on a single association. Like just about everything else in the Ruby on Rails world, there is a ‘Rails way’ to do polymorphic associations. This involves leveraging the support that is built in to Rails’ standard ORM, Active Record. You set up a polymorphic association in very much the same way that you would a typical has_many.
Here are the steps to implement the polymorphic association between these three models.
app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true #…
app/models/post.rb
class Post < ActiveRecord::Base
has_many :comments, as: :commentable #…
app/models/profile.rb
class Profile < ActiveRecord::Base
has_many :comments, as: :commentable #…
migration
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.references :commentable, polymorphic: true #…
end
end
end
Here you can see that all we’re really doing is passing a couple of parameters to the :has_many and :belongs_to methods. The migration will generate two columns on the Comments table, ‘commentable_id’ and ‘commentable_type’. Behind the scenes, Active Record will wire up all of the helper methods that you’re used to using with normal associations. Now the comment model will work as a polymorphic association between Post and Profile model.
And there you have it, both posts and profiles can have their own comments. The obvious limitation here is that, since we’re only setting a single foreign key and type, a comment can only belong to one other object at a time. This may be the desired functionality for some use cases. Sometimes, however, you’ll want to be able to associate a single model with multiple other models of different types at the same time.
Leave a Reply
You must be logged in to post a comment.