A Simple Twitter App with Ruby on Rails – Building Friendships

August 13th, 2009


This is the third and final part of series on how to create a twitter style web application with Ruby on Rails. This part will cover how to add friendships between users.

Self-Referential Relationship


To create friendships between users we have to deal with a special type of association, which is called a self referential relationship. It is called this because the model (in this case, User) references itself. Why? Well if a given “user” has many “friends”, those “friends” are also “users”. Furthermore, each of those friends can also have friends, so we are dealing with a many to many relationship.

The relationship can affectively be called a “friendship” because friendships can be gained and lost (as in real life). So, let’s create the friendship model with two foreign keys.

  > ruby script/generate model friendship user_id:integer friend_id:integer

Now, migrate the database:-

  > rake db:migrate

Making and Losing Friends

Making Friends

We will need to create and destroy friendships and for this we will need a controller for friendships:-

  > ruby script/generate controller friendships

Now add the create and destroy methods as shown below:-

class FriendshipsController < ApplicationController
  def create
    @friendship = => params[:friend_id])
      flash[:notice] = "Added friend."
      redirect_to root_url
      flash[:error] = "Error occurred when adding friend."
      redirect_to root_url
  def destroy
    @friendship = current_user.friendships.find(params[:id])
    flash[:notice] = "Successfully destroyed friendship."
    redirect_to root_url

Making Friends Page

So, what exactly do we relate the user model to?? Well, first we need to specify that the friendship model belongs to a friend (which is actually a user!). You can do this by adding some more lines to the user model:-

class Friendship < ActiveRecord::Base
  belongs_to :friend, :class_name => "User"

We need to add two lines to the User model. A User has many friendships and has many friends through friendships. This reads almost exactly as it is coded, which is a testament to Ruby on Rails.

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships

Listing your Friends

List Friends

If we want to list all the registered users and allow the current user to befriend other users, then we will need to create a new view in the users folder called index.html.erb:-

< % @users.each do |user| %>
< % if user.username != current_user.username %> < %=h user.username %> < %= link_to "Add Friend", friendships_path(:friend_id => user), :method => :post %> < % end %>
< % end %>

Listing Friends Page

Now, let’s put the controller actions in place. Open the users_controller file and add the index and show methods.

class UsersController < ApplicationController
  def index
    @users = User.all
  def show
    @user = current_user

We need to do two more things before we can give this a whirl. First add the friendships resource to the routes file:-

map.resources :friendships

…and finally, we can add some links on the posts/index.html.erb file:-


< %= link_to "Make Friends", users_path %>

< %= link_to "My Friends", { :controller => "users", :action => "show", :id => current_user } %>

Ok, we can now start up the server and browse to http://localhost:3000 to have a look.

Home Page


Obviously there are several directions you could take this application. A lot of features could be added and it could be spruced up, somewhat. I hope these tutorials have helped you in some way and again, I would highly recommend that you try Ruby on Rails, if you haven’t already.

Author: Phil McClure

Phil McClure is a Software Developer from Belfast, Northern Ireland. His main interests are software architecture, design patterns and how these can be applied to web development. Phil blogs at Therailworld. Follow him on Twitter.

Write for Us! We are looking for exciting and creative articles, if you want to contribute, just send us an email.

The jungle is alive: Be it a collaboration between two or more authors or an article by an author not contributing regularly. In these cases you find the Noupe Editorial Team as the ones who made it. Guest authors get their own little bio boxes below the article, so watch out for these.

Tags: ,

23 comments for „A Simple Twitter App with Ruby on Rails – Building Friendships
  1. ijlal on August 13th, 2009 at 3:59 am

    Beautiful code. and very well written tutorial.


  2. Travis Dunn on August 13th, 2009 at 6:04 pm

    I just finished doing some analysis on modeling friendships myself. Here are a few other resources I found useful:

    swemoney’s has_many_friends plugin, which while no longer in active development, is worth reviewing the source code for some ideas for convenience methods and an alternative association model.

    There is also a few excellent questions on stackoverflow addressing this scenario:

    And, of course, Ryan Bates’ railscast:

  3. Daquan Wright on August 13th, 2009 at 11:38 pm

    Don’t work in rails but interesting tutorial nonetheless. Code is quite clear.

  4. used cars ireland on rails on August 14th, 2009 at 1:42 am

    Thanks, simple and well explained.

    • ashiq ali on August 17th, 2009 at 3:15 pm

      how to upgrate my photoshop skill.

  5. Hakim web design on August 14th, 2009 at 11:17 pm

    Every new idea is a new reflexion i will google it

  6. neb on August 15th, 2009 at 4:04 am

    helpful tutorial. Thanks.

  7. dacunk on September 14th, 2009 at 11:42 am


  8. TheWebTuts on October 8th, 2009 at 6:47 pm

    Tutorial added to TheWebTuts

  9. noname on December 5th, 2009 at 4:41 pm

    Is there something missing in this tut?

    Where did you write “Find New Friends”?

  10. Matt on December 20th, 2009 at 6:36 am

    Can you post the code for /users/show.html.erb it’s not in the tutorial

  11. Mike on December 28th, 2009 at 8:55 pm

    Wow this is a great tutorial, thanks.

    One thing though, i noticed i can add the same friend twice. I want to make it so when i go to add friends if a friendship exists then it doesn’t display the friend when i go to find new friends or when i click the add friend it flash[:notice] = “that user is already your friend”. Im assuming this would probably go in the controller but i dont know how to check if a friendship exists.

    • furlan on January 27th, 2010 at 10:35 am

      lol.. just check in if that user is on the array of users

  12. jen on January 19th, 2010 at 9:38 pm

    same question with mike.
    kindly please help me. thanks. :)

  13. Phrozen on February 7th, 2010 at 11:15 am

    Pretty good tutorial, I’m used to Ruby but I’m starting in Rails and this is really a must for starters, it takes you all the way and (i did) let’s you add more things on the go. Some of the code is missing in all tutorials though, makes it hard to follow and sometimes is not easy to figure it out yourself.

  14. vineeth kumar.s on April 26th, 2010 at 3:14 am

    So, what exactly do we relate the user model to?? Well, first we need to specify that the friendship model belongs to a friend (which is actually a user!). You can do this by adding some more lines to the user model:-

    class Friendship “User”

    i think u have misplaced user model instead friendship model ..

  15. Buddy Beers on July 28th, 2010 at 6:50 am

    The problem I see with this method is that friendships are reciprocal. So, if user 1 is listed as friends with user 2 then user 2 must also be friends with user 1. Creating another database entry for this seems redundant. How would you handle this?

    • Benjo on August 31st, 2010 at 9:22 pm

      No it is not redundant. because each row is unique. (Row #1) has user2 as user1’s follower. (Row #2) If they follow each other : user1 as user2’s follower. Easy and simple. (think of difference in facebook and twitter.. in facebook u have to confirm friendship, in twitter u dont)

  16. Daniel on September 4th, 2010 at 2:43 pm

    I’ve worked through this tutorial and got it all working but I want to add a feature and i can’t work out how to do it:

    I’m able to get a list of the people a person is following. But I can’t work out how to get a list of the people following a person…

    that only shows the people being follow by a user…

    I have looked at the SQL table and its storing the links with the user_id and the friend_id… so the above code looks for all records where the is = to user_id in the table…

    I need to be able to access all the records where friend_id = to get a list of people following the user…

  17. Anamaria Feltner on October 13th, 2010 at 1:13 am

    2. Magnificent concept, I used to be impressed and i find your blog extremely detail. In reality, you write them comprehensibly and it can make me understand right away. One factor, I love each word you scribble.

  18. best hemorrhoid treatment on November 14th, 2010 at 2:33 am

    Equipment are available, lots of reflection?Plaza Raekoja Este, helped decide that.The builder is, hair gained or.Get connected directly best hemorrhoid treatment, yards is protected Do not.Is prone to, by tightening your.,

  19. Bada on March 19th, 2012 at 4:13 am

    The action ‘index’ could not be found for FriendshipsController, dont know why i keep having this issue, im using Rails 3