Aug 13

A Simple Twitter App with Ruby on Rails – Building Friendships

Introduction

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

Friends in  A Simple Twitter App with Ruby on Rails – Building Friendships

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

Relationship in  A Simple Twitter App with Ruby on Rails – Building Friendships

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 = current_user.friendships.build(:friend_id => params[:friend_id])
    if @friendship.save
      flash[:notice] = "Added friend."
      redirect_to root_url
    else
      flash[:error] = "Error occurred when adding friend."
      redirect_to root_url
    end
  end

  def destroy
    @friendship = current_user.friendships.find(params[:id])
    @friendship.destroy
    flash[:notice] = "Successfully destroyed friendship."
    redirect_to root_url
  end
end

Makefriends in  A Simple Twitter App with Ruby on Rails – Building Friendships

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"
end

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
  ...
end

Listing your Friends

Crowd in  A Simple Twitter App with Ruby on Rails – Building Friendships

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 %>

Listfriends in  A Simple Twitter App with Ruby on Rails – Building Friendships

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
  end

  def show
    @user = current_user
  end
  ...
end

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 in  A Simple Twitter App with Ruby on Rails – Building Friendships

Summary

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.

Phil Mcclure Small in  A Simple Twitter App with Ruby on Rails – Building Friendships

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.

Tags: ,

19 Responses, Add Comment +

  1. ijlal 13 August 2009

    Beautiful code. and very well written tutorial.

    Thanks.

  2. Travis Dunn 13 August 2009

    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.

    http://github.com/swemoney/has_many_friends/tree/master

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

    http://stackoverflow.com/questions/623909/rails-model-with-foreignkey-and-link-table/623956#624261

    http://stackoverflow.com/questions/1071014/rails-two-way-friendship-model-contd

    And, of course, Ryan Bates’ railscast:

    http://railscasts.com/episodes/163-self-referential-association

  3. Daquan Wright 13 August 2009

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

  4. Thanks, simple and well explained.

    • ashiq ali 17 August 2009

      how to upgrate my photoshop skill.

  5. Hakim web design 14 August 2009

    Every new idea is a new reflexion i will google it

  6. neb 15 August 2009

    helpful tutorial. Thanks.

  7. dacunk 14 September 2009

    nice!!

  8. TheWebTuts 8 October 2009

    Tutorial added to TheWebTuts

  9. noname 5 December 2009

    Is there something missing in this tut?

    Where did you write “Find New Friends”?

  10. Matt 20 December 2009

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

  11. Mike 28 December 2009

    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 27 January 2010

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

  12. jen 19 January 2010

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

  13. Phrozen 7 February 2010

    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.

Trackbacks

Leave a Reply

Comments are moderated – and rel="nofollow" is in use. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!