Allowing Users to Follow Users, Self Join tables in Ruby on Rails

Riley Iverson
3 min readMay 13, 2021

The core feature in any social media platform is having the ability to let users follow other users, and to see posts that those users made in your own feed. A while back I made a social media app for my boot camp final, which used Ruby on Rails and has a follow feature. In this article I’ll show how I was able to implement this surprisingly confusing feature.

A visual example of a Users table with a Relationships self-join table

So how do we allow users to follow each other in terms of our database? Of course we’ll have a user table, but how do we make a way for this table to connect to itself? Like the title suggests, we’ll use a join table. Specifically users will have many of this relationship table, and this relationship table will have many users. This join table will store two user ids, a follower id (the person who clicked the follow button), and the followee id (the person who is being followed). The users table won’t need anything special since the rest of the relationships will be handled in the models.

A schema showing the users table and relationships table in the SQL database.

Now that we have our tables setup in our database, we’ll set up our user model. In this model we want to get access to two things: the people we’re following, and the people who are following us. Here is the code that I wrote:

The core connections to create the following and followed users in the User model file.

From the top the followed_users is that join table we made, connecting us and all the users we’re following. The next line, followees are users that we’re following. If we wanted to access all of the users that user A follows, we would use “A.followees.all”. The next two lines are the exact same idea but for the users that are following us. Following_users is that join table we made, and followers is all the users following us. Similarly we could access all of user A followers by using “A.followers.all”.

The last thing we need to finish is the relationship model. All that’s in this file are two belongs_to lines, Belongs_to :follower with the classname of user and belongs_to :followee with the classname user. And that’s it. Now users can follow other users, and we can find which users are following others and vice versa.

Final relationship lines needed in the Relationship model file.

I hope you’ve learned something from this, and that it made understanding self-joins just a little bit easier. Implementing this is a great way to add a social aspect to your applications and can be fun and interactive for your users.

--

--

Riley Iverson

A Software Developer specializing in React.js and Ruby on Rails.