Introduction
In this tutorial, we will walk through the process of building a social media app using Ruby on Rails. We will cover the basics of setting up a Rails application, creating models and associations, implementing user registration and authentication, and building the core functionality of a social media app, including posting and commenting.
By the end of this tutorial, you will have a working social media app that allows users to create accounts, make posts, and interact with other users’ posts through comments.
Prerequisites
Before we begin, make sure you have the following installed on your machine:
- Ruby (version 2.7.3 or higher)
- Ruby on Rails (version 6.1.4 or higher)
- PostgreSQL (version 9.5 or higher)
Step 1: Setting Up the Rails Application
Let’s start by creating a new Rails application. Open your terminal and run the following command:
rails new social_media_app
This will generate a new Rails application in a directory called social_media_app
. Change into the application directory by running:
cd social_media_app
Step 2: Setting Up the Database
Next, we need to set up the database for our application. Open the config/database.yml
file and configure the database connection settings based on your local setup.
default: &default
adapter: postgresql
encoding: unicode
username: YOUR_USERNAME
password: YOUR_PASSWORD
host: localhost
port: 5432
development:
<<: *default
database: social_media_app_development
test:
<<: *default
database: social_media_app_test
production:
<<: *default
database: social_media_app_production
Make sure to replace YOUR_USERNAME
and YOUR_PASSWORD
with your PostgreSQL username and password.
Run the following command to create the development and test databases:
rails db:create
Step 3: Generating User Model and Authentication
We will be using the popular Devise
gem for user authentication. Add Devise
to your Gemfile
by uncommenting the line:
gem 'devise'
Save the file and run the following command to install the gem:
bundle install
Next, generate the Devise configuration files and the User model by running the following command:
rails generate devise:install
This will generate the initial configuration files and the User model.
Migrate the database to create the necessary tables for Devise by running:
rails db:migrate
Next, generate the views and controller for User registration by running:
rails generate devise:views
rails generate devise:controllers users
Step 4: Creating Associations
Now that we have the User model set up, let’s create the other models and associations needed for our social media app.
Generate the Post model by running the following command:
rails generate model Post content:text user:references
The content
attribute will store the content of the user’s post and the user_id
will be used to associate the post with the user who created it.
Migrate the database to create the posts table by running:
rails db:migrate
Next, generate the Comment model by running the following command:
rails generate model Comment content:text user:references post:references
The content
attribute will store the content of the user’s comment, the user_id
will be used to associate the comment with the user who created it, and the post_id
will be used to associate the comment with the post it belongs to.
Migrate the database to create the comments table by running:
rails db:migrate
Define the associations in the models as follows:
# app/models/post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :comments
end
# app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
end
# app/models/user.rb
class User < ApplicationRecord
# ...
has_many :posts
has_many :comments
end
Step 5: Generating Controllers and Views
Now that our models and associations are set up, let’s generate the controllers and views for our posts and comments.
Generate the Posts controller by running the following command:
rails generate controller Posts
Now, open the app/controllers/posts_controller.rb
file and define the actions for creating, showing, and deleting posts:
class PostsController < ApplicationController
before_action :authenticate_user!
def index
@posts = Post.all.order(created_at: :desc)
end
def new
@post = current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to posts_path, notice: 'Post was successfully created.'
else
render :new
end
end
def show
@post = Post.find(params[:id])
@comment = Comment.new
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_path, notice: 'Post was successfully destroyed.'
end
private
def post_params
params.require(:post).permit(:content)
end
end
Next, generate the Comments controller by running the following command:
rails generate controller Comments
Open the app/controllers/comments_controller.rb
file and define the actions for creating and destroying comments:
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(comment_params)
@comment.user = current_user
if @comment.save
redirect_to post_path(@post), notice: 'Comment was successfully created.'
else
redirect_to post_path(@post), alert: 'Comment could not be created.'
end
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to post_path(@comment.post), notice: 'Comment was successfully destroyed.'
end
private
def comment_params
params.require(:comment).permit(:content)
end
end
Step 6: Creating the Views
Now that our controllers are set up, let’s generate the views for our posts and comments.
Create a new file called index.html.erb
in the app/views/posts
directory and add the following code:
<h1>Posts</h1>
<%= link_to 'New Post', new_post_path %>
<% @posts.each do |post| %>
<div>
<h2><%= post.user.email %></h2>
<p><%= post.content %></p>
<%= link_to 'View', post_path(post) %>
<% if post.user == current_user %>
<%= link_to 'Delete', post_path(post), method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
</div>
<% end %>
Create a new file called show.html.erb
in the app/views/posts
directory and add the following code:
<h1>Post</h1>
<h2><%= @post.user.email %></h2>
<p><%= @post.content %></p>
<h3>Comments</h3>
<% @post.comments.each do |comment| %>
<div>
<h4><%= comment.user.email %></h4>
<p><%= comment.content %></p>
<% if comment.user == current_user %>
<%= link_to 'Delete', comment_path(comment), method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
</div>
<% end %>
<%= form_with(model: [@post, Comment.new]) do |form| %>
<%= form.text_field :content %>
<%= form.submit 'Add Comment' %>
<% end %>
Create a new file called new.html.erb
in the app/views/posts
directory and add the following code:
<h1>New Post</h1>
<%= form_with(model: @post) do |form| %>
<%= form.text_area :content %>
<%= form.submit 'Create Post' %>
<% end %>
Create a new file called _comment.html.erb
in the app/views/comments
directory and add the following code:
<p><%= comment.content %></p>
<%= link_to 'Delete', comment_path(comment), method: :delete, data: { confirm: 'Are you sure?' } %>
Finally, modify the app/views/layouts/application.html.erb
file to include a link to the posts index page:
<!DOCTYPE html>
<html>
<head>
<title>Social Media App</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<header>
<%= link_to 'Home', posts_path %>
<% if user_signed_in? %>
Logged in as: <%= current_user.email %>
<%= link_to 'Logout', destroy_user_session_path, method: :delete %>
<% else %>
<%= link_to 'Login', new_user_session_path %>
<% end %>
</header>
<main>
<%= yield %>
</main>
</body>
</html>
Step 7: Testing the Application
Start the Rails server by running the following command:
rails server
Open your web browser and visit `http://localhost:3000`. You should see the posts index page. If you try to create a new post or comment without logging in, you will be redirected to the login page. Sign up for a new account and try creating posts and comments.
Congratulations! You have successfully built a social media app with Ruby on Rails.
Conclusion
In this tutorial, we covered the process of building a social media app using Ruby on Rails. We walked through setting up a Rails application, creating models and associations, implementing user registration and authentication using Devise, and building the core functionality of a social media app including posting and commenting.
From here, you can extend the functionality of your social media app by adding features such as likes, followers, and user profiles.
Happy coding!