Self-referential-many-to-many relationship in Ruby on Rails

Code, code, code ……

In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all users in a single database model, this situation can be modeled with self-joining associations. Self referential associations is used in many social-networking web apps, in which we create friends-join-table, a user can have many followers, and the user can follow many friends.

For my final project in Flatiron school “Therappoint”, an appointment-booking-app between therapy providers and clients, I used self joins to establish the relationship between providers and clients.

Next, I’ll explain how to establish the relationship from scratch.


For user table, we need to add all attributes for both providers and clients;

User table migration

For join-table, in my case, it’ll be appointment table. First we don’t need to add foreign key column.


Before “rails db:migrate”, we need to write following in the models.

User model

In line 2, I created the relationship that, “client” has many “provider_appointments”, (we can’t use has many “appointments”, otherwise appointment wouldn’t be able to differentiate appointments from different users), after “client” has many “provider_appointments”, we created the relationship between “client” and “providers”, a “client” has many “providers” through “provider_appointments”. The same, we created a “provider” has many “clients” through “client_appointments”.

The appointment model is simple.

Appointment model

Since the models are ready, now we could add foreign key for appointment table.

After finished above files, now we could “rails db:migrate”.

Let’s see what our schema looks like now.

Image for post
Image for post

To make sure it’s working, let’s test it!

Image for post
Image for post
Creating Client
Image for post
Image for post
Creating Provider
Image for post
Image for post
Relating client and provider with appointment


Written by

Multi-human-lingual and multi-programming-lingual |

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store