Many to Many Ruby Guide

Jesus Garcia
3 min readJan 12, 2021

--

Many to Many relationships are confusing and sometimes complicated to understand. I had the most trouble with this and this was the way I was able to better understand it. Here we will use Artist, song, and genre as an example. An artist can have many genres, and many genres can have many artists. The joiner will be the song. A song belongs to the artist and belongs to the song.

Many to Many Association — Here we have 3 models being joined through the many to many association. We want to join them but we are a little confused with the has_many and has_many through. First we have to notice that a has many to many relationship is the equivalent of two, one to many relationships. So first lets take care of the basics.

Belongs To — One model belongs to the other. Object wise, one object can belong to one object from the other model. Here we can see that a song belongs to one artist. A song belongs to a genre. Also, we can see that an Artist has many songs and a genre has many songs.

Has Many — One object has many of the other. One object can contain many objects from another model. We can also see that an Artist can have many songs

Here is our many and belongs to associations together.

To make this a Many to Many relationship, we just need to add the last association, which is “through”. An artist has many genres through songs. A genre can have many artists through a song.

Another way that I like to break it down that makes more sense to myself is like this:

Lets take this example of multiple has many relationships! At first it looks very overwhelming!

First try and separate them into more simple relationships!

As you can tell, now we can see that our overwhelmingly looking model association doesn’t look so complicated anymore. Now we can look at 3 different associations instead of 1 big mess.

Then after having 3 different relationships, you can further break them down into belongs to and many relationships. This is much more easier to look at then an entire map of multiple relationships.

In conclusion the associations can be broken down into its simpler versions. This will really help out when trying to associate multiple relationships and models.

--

--