Rails Database Associations - Polymorphism vs many_to_many

As a new student of Rails, I was slow to wrap my head around the difference between polymorphic associations and 'many_to_many' via has_many :through (HMT) associations using ActiveRecord. Are they complementary or mutually exclusive? Do polymorphic associations use many_to_many relationships? And are join tables always needed? Allow me to present my findings...

Rails many_to_many relationships, built using HMT associations, allow a model to be connected to multiple instances of another model. So we're talking about TWO models, but with any number of instances of those models. The many_to_many aspect dictates that multiple instances of a model can be associated with another model. If you wanted to associate a second model with the first (for a total of 3 models) without polymorphism, this would require an additional association and foreign key to be introduced. Here's an example of a many_to_many setup at the model level, where a newspaper can have many articles, and an article can be in many newspapers (many_to_many associations do require a join table):





Polymorphic associations allow a model to be connected to TWO OR MORE other models via a single association. Whether or not those models have many_to_many relationships is not a direct concern of polymorphism. Polymorphism is concerned with relationships between three or more models, but does not explicitly determine how many instances of those models can be connected. Polymorphic associations do not require join tables for setting up the polymorphic relationship, but a join table will be needed if those models use a many_to_many connection. Let's look at an example of polymorphism using many_to_many associations. Our newspaper example will now focus on tags, which can be associated with both newspapers and articles. We need to use many_to_many associations because a tag can have many articles and newspapers, and newspapers and articles can have many tags (in this example, articles and news papers are no longer directly connected):

So to summarize, polymorphism is useful when a model needs connections to multiple other models, but does not determine the type of associations between instances of those models. Many_to_many associations deal with instances of models, and this concept is neither exclusive of nor dependent on polymorphism. A polymorphic model could use a many_to_many assoction, OR a has_one assoction, etc. I'll wait until my next post to explore keeping articles and news papers directly connected while also implementing the polymorphic tag associations.

Please enable JavaScript to view the comments powered by Disqus.

Disqus