Many to Many Relationship — Ruby

Hanna Mulugeta
Nerd For Tech
Published in
3 min readMar 26, 2021

When we examine their relationship, we notice that a doctor can see many patients and a patient also can be seen by many doctors. In this relationship, unlike the belongs to relationship, it is difficult to put a reference of one object in to the other, as one doesn’t solely belongs to the other object. In this kind of scenario, to create a relationship between the entities, we have to create another entity that can hold a single instance of both objects. We call this a Join Entity. For our case, let us create an Appointment join entity.

The entity diagram is a bit high level explanation of the has-many-through relationship, which contain active record macros, (I will discuss it in my next article).

So as seen in the diagram, an instance of an appointment is surely belongs to a doctor and also to a patient. Using this joint table we can create an indirect relationship between a doctor and a patient. This will enable us to get a useful information out of each. If for example a doctor want to know the list of his patients, we can directly find that information through the appointments table. Same with patients, they can retrieve the list of their doctors, by going through the join table.

Let’s view them using ruby codes.

A Patient and Doctor classes are instantiated with their attributes up on initialization. Because of the join class Appointment, see below, we are able to create new behaviours/methods like new_appointment, that enable both classes to hold new appointments, both can view list of their appointments, and a doctor are able to see list his patients and vise versa.

The Join class, Appointment, has the patient and doctor instances captured for every instance of an appointment. Those are being pushed to an array class variable. Which enable us to iterate over it, whenever we want an information about each entities.

The previous and this article shows a very low level but basic explanation of the belongs_to/ has-many and the has-many-through relationship. If we are able to correctly map the relationship between any real world objects, we can capture a very dynamic data that will enable us to solve real world problems.

--

--

Hanna Mulugeta
Nerd For Tech

Software Engineering Student @ Flatiron School, with a base knowledge and experience of Application and System Analysis in aviation industry.