Loads of modern apps employ some sort of friends list feature. The ability to create relationships among users has become a common-place practice that brings people together via technology. In this blog I am going to share what I believe is the simplest way to implement associations amongst users via friend requests and a friends list.
As a student of Flatiron’s software engineering course, we are challenged with completing five projects during our 15 week program. Both my second and third projects implemented a friend’s list feature. I did a good deal of research on how to implement friends lists. Ultimately my group members and I were able to come up with a method that I believe to be the easiest to understand as well as code. I am using a rails api for my backend and vanilla javascript for my front.
This method uses two models: users and friends list.
Seen above is a diagram to help you visualize this relationship. The User class has two subclasses called as_receiver and as_requestor which act like separate models themselves. FriendRequest acts a join table between our two User subclasses.
Inside of these models we can create their associations using these keywords:
As you can see there is only one User model, but when we define a relationship in this manner we get two subclasses associated between FriendRequest and User.
Once these relationships are created we have to add their IDs into the migration files:
Notice I didn’t add anything special into my CreateUsers table
CreateFriendRequests is where the magic happens. We now have two User ID’s being associated through this table. The user that initiates the friendship is stored into the requestor_id slot while the receiver of that friend request is stored into receiver_id. Status will have one of two possibilities: “pending” and “accepted”.
This would be the logic behind an add friend button. A post request is made to create an instance of FriendRequest which associates the current user as_requestor with another user as_receiver.
After that is done it doesn’t take much to show pending requests. Iterating through all FriendRequests(request=each iteration):
else if ((request.requestor.id == u1.id || request.receiver.id == u1.id) && request.status == 'pending'){
Accepting the request simply makes a patch request to our rails backend to change the status of the request to “accepted”
Declining the request is even simpler as it just destroys that friend request altogether:
Once the request is accepted its as easy to show as it was to show pending requests.
if ((request.requestor.id == u1.id || request.receiver.id == u1.id) && request.status == 'accepted'){
I hope this blog is useful for anyone who is looking to implement a friends feature in their program!
Top comments (0)