How to Use Self-JoinTables in Rails

JakePino
3 min readMay 5, 2020

--

When working on a project this week that involved users and followers, my partner and I were pointed toward looking into self-join tables. If you think about how users and followers work in most applications, it looks and act a lot like a many-to-many data model. A user has many followers, as well as follows many users. But how does that look when setting up our tables? A user has many followers and… a follower has many users? No, that’s doesn’t seem right, so how about a user has many users? That’s still doesn’t work, as setting up that relationship leads to all kinds of errors. We clearly need a join table of some kind, but specifically what we need is a join table that links users to other users through referencing itself. This is known in Rails as a Self-Join table, AKA a Self-Referential Table.

The way the self-join table works is just like most join tables, only with some key differences. We first made a join table in our database, naming it “Follow”. We gave it two ids, but instead of it being two user_ids, we gave it a “follower_id” and a “followee_id”. We can more or less name these anything, as long as the developer and anyone working on the project can clearly keep track of what’s going on.

Next, when setting up the relationship through our models, we want to see it up so that it looks something like this:

This tells the Follow model that it belongs to both a follower and a followee, which can be found in the “User” class, through its id.

Next if we look at how this affects the User model, it looks a little different as well. We need to set up a relationship where a User has many followers, with a foreign_key belonging to Follow, and the same with followees. Which looks something like this.

Breaking it down, a User has many “followed_users”, i.e. they are following many other users, by association with the “follower_id” foreign key through the Follow class. Line 2 states that a User has many “followed_users”, so they also have many “followees” through that “followed_user”. Lines 3 and 4 point to all the followers that User has by repeating the same process.

And there we have it, our Self-Join table is set up and a User can start following and receiving followers!

--

--

JakePino
JakePino

Written by JakePino

California native, living in NYC., Software Engineer.

No responses yet