Polymorphic associations in Rails

by Michael McClenaghan 2007-04-08

Lately I've been playing with a few of the "acts_as_..." plugins that are available for Rails. Specifically, acts_as_rateable, acts_as_taggable and acts_as_commentable.

All of these share one major feature in common - they take advantage of the ability for Rails to support polymorphic associations. Expressed a different way, they all support has_many :whatevers.

To quote the Rails wiki:

Polymorphic associations are promiscuous associations—that is, they are unrestricted in terms of what other classes the association can be with. Polymorphic associations allow for associations from one model to other model classes(note the plural).

The wiki has some good articles that will help you to understand polymorphic associations and when you should use them. While they introduce a lot of flexibility, they could also have some performance problems in larger sites.

This is just one more reason why I'm impressed with this framework. What will they think of next?

blog comments powered by Disqus