How to Build a social network using Ruby on Rails

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.
[xml]<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>

[/xml]

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.

[xml]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[/xml]

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

[xml]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
[/xml]

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

[xml]<%= 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 %>
[/xml]

Post controller.rb

[xml]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
[/xml]

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

  • 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:

[xml]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
[/xml]

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:

[xml]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
[/xml]

Form views:

Likes:

[xml]<% 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 %>
[/xml]

Comments:

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

[xml]<divclass=”form-group”>
<%= text_area_tag:comment_text, nil, placeholder:’Enter Comment’, class:’form-control’ %>
</div>

<%= submit_tag:comment, class:’btnbtn-primary’ %>
<% end %>
[/xml]

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:

[xml]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
[/xml]

Follow view:

[xml]<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>

[/xml]

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:

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

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

<div>
[/xml]

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:

[xml]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
[/xml]

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:

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

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.