Build a Social Network Using ROR

Developers need a basic understanding of Ruby on Rails, CoffeeScript, and PostgreSQL. This article can help you understand how to build a social network using Ruby on Rails.

Prerequisites

  1. Ruby & Rails: https://gorails.com/setup
  2. Postgres: https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-14-04
  3. Herokutoolbelt: https://toolbelt.heroku.com/
  4. Git(Optional):http://git-scm.com/downloads

Think about the common feature that is required for every social network platform. Every social media network has posts in the feeds. Isn’t it? Any good social media platform would provide real-time updates of posts in the user feeds. All the users get access to the posts and latest information on their profiles.

Start Hacking

You can start building social networking app with RoR by running command that creates the Rails application with default gems that are mentioned in the code file. The command is rails new app_name.

First thing need to do after running command is modifying the gemfile by adding and removing gems from the list of defaults.

1. Run Rails:

The view pages are not present yet we can run the rails server to get the initial start by running command: rails server OR rails s

This will display the default landing page of rails.

2. Asset Pipeline:

There are various default assets file present. We can add those required as per the application requirement. If one needs to add custom JS or CSS, then the main files to add these are application.css and application.js.

@import "bootstrap-sprockets";
@import "bootstrap";
@import "font-awesome";
@import "jquery.datetimepicker";
@import "*";
//= requirejquery
//= require jquery_ujs
//= require bootstrap
//= require bindWithDelay
//= require jquery.datetimepicker
//= require_tree.
<navclass="navbarnavbar-default navbar-fixed-top">
<divclass="container">
<divclass="navbar-header">
<buttontype="button"class="navbar-toggle collapsed"data-toggle="collapse"data-target="#navbar-top">
<spanclass="sr-only">Toggle navigation</span>
<spanclass="icon-bar"></span>
<spanclass="icon-bar"></span>
<spanclass="icon-bar"></span>
</button>
<%= link_to"Socify", root_url, class:"navbar-brand" %>
</div>

<divclass="collapse navbar-collapse"id="navbar-top">
<ulclass="navnavbar-navnavbar-right">
<% ifuser_signed_in? %>

<li><%= link_to('Sign out', destroy_user_session_path, method::delete) %></li>

<% else %>

<li><%= link_to'Sign up', new_user_registration_path %></li>


<li><%= link_to'Sign in', user_session_path %></li>

<% end %></ul>

</div>

</div>

</nav>

To avoid landing into the welcome abroad page, you can create your own controllers and its respective views folder for managing your landing page.

It can be done by the following command:

Rails generate controller home index

And

These lines into the routes.rb file:

Rails.application.routes.draw do
  Root to: "home#index"
end

3. Authentication

The best option for adding authentication and authorization in rails application is by adding gem named: DEVISE. This provides awesome property of security, authentication, and maintaining session for servers. Run the command: rails g devise:install. After this, we need to create the user model by running command: rails g devise user. For adding migration of user model, run command: rake db:migrate.

classDeviseCreateUsers<ActiveRecord::Migration
defchange
create_table(:users) do |t|
t.string:name,               null:false, default:""
t.string:email,              null:false, default:""
t.string:encrypted_password, null:false, default:""
t.string:about
t.string:avatar
t.string:cover

t.string:reset_password_token
t.datetime:reset_password_sent_at

t.datetime:remember_created_at

t.integer:sign_in_count, default:0, null:false
t.datetime:current_sign_in_at
t.datetime:last_sign_in_at
t.string:current_sign_in_ip
t.string:last_sign_in_ip

t.string:confirmation_token
t.datetime:confirmed_at
t.datetime:confirmation_sent_at

t.timestampsnull:false
end

add_index:users, :email,                unique:true
add_index:users, :reset_password_token, unique:true
add_index:users, :confirmation_token,   unique:true
end
end

The main questions arrives about customizing the gem, Yes it is customizable. To generate views run the command: rails g devise:views. This generates the folder for all view files, now we can modify accordingly.

classApplicationController<ActionController::Base

protect_from_forgerywith::exception
before_filter:configure_permitted_parameters, if::devise_controller?
protected
defconfigure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << [:name, :password_confirmation]
devise_parameter_sanitizer.for(:sign_in) << [:email, :remember_me]
end
end

4. Posts & Events

Number of users those have registered on signed up needs the way to post the matter they want to. Here comes the posts module into reference, for generating post module run command:

Rails g scaffold post attachment:stringcontent:textuser:reference
Rake db:migrate

The above command will generate the complete structure including controller, model with attributes attachment, content and user ID and view files with all CRUD operations. One can add bootstrap and change the view file style accordingly.

5. Create Post:

As all files and methods are prebuilt due to scaffold command, so by going to new post, new post can be created and that will be displayed in the index page that is listing page of posts.

Form.html.erb

<%= form_for(@post) do |f| %>
<divclass="form-group">
<%= f.label'Update status' %>
<%= f.text_area:content, class:'form-control', autofocus:true, placeholder:'What\'s up?' %>
<%= f.file_field:attachment, class:'form-control' %>
</div>

<%= f.submit:post, class:'btnbtn-primary'%>
<% end %>

Post controller.rb

Def create
@post=Post.new(post_params) do |post|
post.user=current_user
end
if @post.save
redirect_toroot_path
else
redirect_toroot_path, notice: @post.errors.full_messages.first
end
end

6. Carrier wave

Carrier wave is the rails gem used for uploading and saving any kind of files.

Run following command for integrating carrier wave into code.
Rails g uploaderavtar

This adds the below code to post model file:

Class Post <ActiveRecord::Base

Mount_uploader :attachment, Avataruploader

End

7. Create Event:

Creating event is similar as creating posts. This includes the timings and date so we need to add the date time picker gem of rails. By using jQuery plugin https://github.com/xdan/datetimepicker one can add datetimepicker to the form, just this thing to add is its assets into our code application.css and application.js.

Top 10 Web Apps that are Built Using Ruby on Rails

Top 10 Web App Build in ROR

  • AirBnB: Hospitality Service
  • Basecamp: Project Management
  • GitHub: Version Control Repository
  • SoundCloud: Online Music Distribution
  • Slideshare: Slide Hosting Service
  • Crazy Egg: Visual Website Analytics and Heatmap
  • Shopify: Online Stores (SAAS Model)
  • Hulu: Live Video Streaming
  • Fiverr: Freelance Marketplace
  • GoodReads: Social Cataloging

Likes & Comments

1. Likes:

For adding likes, Ruby on rails provides the gem named, act as votable which through giving votes we can count the number of likes.

Just run the below command for adding gem:

Rails generate acts_as_votable:migration
Rake db:migrate

Handle like and dislike:

classLikesController<ApplicationController
before_action:find_likeable
before_action:authenticate_user!
respond_to:js

defcreate
    @likeable.liked_bycurrent_user
end

defdestroy
    @likeable.disliked_bycurrent_user
end

private
deffind_likeable
    @likeable_type=params[:likeable_type].classify
    @likeable= @likeable_type.constantize.find(params[:likeable_id])
end
end

2. Comments:

Similar to adding likes, there is a gem provided by rails to add comments to any posts or articles.

Run the below command for same:

Rails g comment
Rake db:migrate

Then after generation of comment model add acts_as_commentable to the same model.

Handle comments create and delete actions:

classCommentsController<ApplicationController
before_action:authenticate_user!
before_action:find_commentable, only::create
respond_to:js

defcreate
    @comment= @commentable.comments.newdo |comment|
comment.comment=params[:comment_text]
comment.user=current_user
end
    @comment.save
end

defdestroy
    @comment=current_user.comments.find(params[:id])
    @comment_id=params[:id]
    @comment.destroy
end

private
deffind_commentable
    @commentable_type=params[:commentable_type].classify
    @commentable= @commentable_type.constantize.find(params[:commentable_id])
end
end

Form views:

Likes:

<% ifcurrent_user.liked? likeable %>
<%= form_tagunlike_path(likeable_type:likeable.class.to_s, likeable_id: likeable.id), method::post, remote:truedo %>
<% button_tagclass:'btnbtn-block liked'do %>
<%= fa_icon'thumbs-up' %> unlike
<% end %>
<% end %>
<% else %>
<%= form_taglike_path(likeable_type:likeable.class.to_s, likeable_id: likeable.id), remote:truedo %>
<% button_tagclass:'btnbtn-block'do %>
<%= fa_icon'thumbs-up' %> like
<% end %>
<% end %>
<% end %>

Comments:

<%= form_tagcomments_path(commentable_type:commentable.class.to_s, commentable_id: commentable.id), method::post, remote:truedo %>

<divclass="form-group">
<%= text_area_tag:comment_text, nil, placeholder:'Enter Comment', class:'form-control' %>
</div>

<%= submit_tag:comment, class:'btnbtn-primary' %>
<% end %>

Relationships:

In any of the social networking app, relations are most important attributes to be added on. So far we have created posts, events, liked and commented those posts and events. Now for maintaining relationship we need to add another rails gem named: acts_As_follower.

Rails generate acts_as_follower
Class User <ActiveRecord::Base
Acts_as_follower
Acts_as_followable

End

That’s it now any user can follow us and we can follow them.

Follow controller:

classFollowsController<ApplicationController
before_action:authenticate_user!
respond_to:js

defcreate
    @user=User.find(params[:user_id])
current_user.follow(@user)
end

defdestroy
    @user=User.find(params[:user_id])
current_user.stop_following(@user)
end
end

Follow view:

<divclass="follow">
<% ifuser.followed_by?(current_user) %>
<%= form_tagunfollow_path(user_id: user.id), method::post, remote:truedo %>
<%= button_tag'unfollow', class:'btnbtn-primary' %>
<% end %>
<% else %>
<%= form_tagfollow_path(user_id: user.id), method::post, remote:truedo %>
<%= button_tag'follow', class:'btnbtn-success' %>
<% end %>
<% end %>
</div>

Public Activity

If one needs to keep track of all the activities about which user has liked, commented, shared or followed, there’s a gem provided by rails i.e., public_activity gem.

Rails g public_activity:migration
Rake db:migrate

Home controller for tracking public activity:

classHomeController<ApplicationController
respond_to :html, :js
def index
    @activities = PublicActivity::Activity.all
  end
end

<div id="activities">
<%= render_activities(@activities)%>

<div>

Newsfeed

Newsfeeds differ for every user session. When user logs in it, he/she lands to the index page with listings of posts. After increasing users posts counts also increases parallel there by increasing the page load time. So it is suggested to use pagination for managing a large number of listing and it consumes less amount of page load time. Rails provides gem for same, i.e., will_paginate.

Home controller:

classHomeController<ApplicationController
before_action:set_user, except::front
respond_to:html, :js
defindex
    @post=Post.new
    @friends= @user.all_following.unshift(@user)
    @activities=PublicActivity::Activity.where(owner_id: @friends).order(created_at::desc).paginate(page:params[:page], per_page:10)
end
deffront
    @activities=PublicActivity::Activity.order(created_at::desc).paginate(page:params[:page], per_page:10)
end

deffind_friends
    @friends= @user.all_following
    @users=User.where.not(id: @friends.unshift(@user)).paginate(page:params[:page])
end
private
defset_user
    @user=current_user
end
end

Deploy

When it comes to deployment, heroku is considered as the best and the most easiest way to deploy any ruby and rails application. There are below commands used for initial deployment to heroku:

Heroku login   // create account on heroku and login through same
Herokugit:remote –a [app_name]
Git push heroku master
Heroku run rake db:migrate

Helpful reading – How to Speed Up Ruby on Rails App Performance

Now, everything is deployed to heroku and sounds good in every way.

If you are looking for Ruby on Rails social network, you can get in touch with us and we shall be glad to assist you.

Post Comment

Your email address will not be published. Required fields are marked *

Please type your comment