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;
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.
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.
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.
To make sure it’s working, let’s test it!
At first, it seems a bit complicated, but as long as you getting the “naming” clear, it will get easier!