Many to Many Relationships in Rails using Active Record

Payton Gray
2 min readOct 8, 2020

Thank you for visiting this post! Be sure to also take a look at my other work on LinkedIn and Github.

Learning anything new can be daunting sometimes. So let me make it easier on you and explain this the best I can. A many to many relationship has 2 models that have a has_many association to each other.

How to set up your models

The way to set up a many to many relationship is through your models. You already know about the two, many to many models. Now we need a joiner model. The joiner model will act as the connection to each of the other models. When creating a joiner class the class will belong_to the classes it is connecting. For example: see pets model in picture below. Pets would be our joiner model. It belongs to both of the other classes Vet and Owner.

In the models you have a has_many association through: the joiner model. In this situation a vet can have many owners through: pets and owners can see many vets through pets. So in both of our models we will create a has_many connection to our pets joiner. Then we will make a has_many connection to the other model through: our joiner model. Example below in the Owner and Vet model.

With the help of Active Record has_many :through association, I can now use methods provided by Rails.

See its not so hard. Sometimes we just need to break it down to see how it all works. Thank you for reading through this tutorial!

--

--