How to Build a Simple CRUD Application with Ruby on Rails
Ruby on Rails (RoR) is a powerful web application framework that follows the Model-View-Controller (MVC) pattern, making it easy to build scalable applications quickly. In this guide, we will walk through creating a simple CRUD (Create, Read, Update, Delete) application from scratch, allowing users to manage basic data entries.
Prerequisites
Before we start, ensure you have the following:
- Ruby installed (version 2.5.0 or higher).
- Rails installed (version 5 or higher).
- A working PostgreSQL or SQLite setup (we'll use SQLite for simplicity).
- Basic knowledge of Ruby and Rails command-line tools.
If you haven't installed Rails yet, run:
gem install rails
Step 1: Create a New Rails Application
The first step is to create a new Rails application. Open your terminal and run:
rails new crud_app --database=sqlite3
cd crud_app
This creates a new Rails application named crud_app
with SQLite as the default database.
Step 2: Generate a Scaffold
In Rails, a scaffold automatically generates all the necessary files for a basic CRUD interface. For this example, let’s create a scaffold for managing "Posts" (like blog posts).
Run the following command:
rails generate scaffold Post title:string content:text
This generates a model (Post
), controller, views, and routes. The model will have two fields: title
(string) and content
(text).
Next, run the database migration to create the necessary table:
rails db:migrate
Explanation:
- rails generate scaffold: This command creates the full set of files needed for CRUD functionality.
- title:string content:text: Specifies the fields and their data types for the Post model.
- rails db:migrate: Applies the migration to create the
posts
table in your SQLite database.
Step 3: Start the Rails Server
To see your CRUD app in action, start the Rails server:
rails server
Now, open your browser and navigate to http://localhost:3000/posts
. You’ll see the scaffold-generated UI that allows you to create, read, update, and delete posts.
Step 4: Understanding the CRUD Operations
1. Create:
The scaffold provides a form for creating new posts. Click on “New Post” and fill out the form to add a new post.
The create
action in the PostsController
handles the form submission:
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: 'Post was successfully created.'
else
render :new
end
end
2. Read:
Once a post is created, you can view it by clicking on the post title. The show
action in the PostsController
fetches the post and displays it:
def show
@post = Post.find(params[:id])
end
3. Update:
You can edit a post by clicking “Edit” on the post's page. The update
action processes the form submission and updates the post:
def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to @post, notice: 'Post was successfully updated.'
else
render :edit
end
end
4. Delete:
You can delete a post by clicking “Destroy” on the post's page. The destroy
action removes the post from the database:
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_url, notice: 'Post was successfully destroyed.'
end
Step 5: Customizing the Views
The scaffold generates basic HTML views, but you can customize them to match your design preferences. The views for posts are located in app/views/posts/
.
For example, if you want to modify the form used for creating and editing posts, open app/views/posts/_form.html.erb
:
<%= form_with(model: post, local: true) do |form| %>
<% if post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :title %>
<%= form.text_field :title %>
</div>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
You can modify the HTML or add your own classes and styles to make the form look the way you want.
Step 6: Add Validation to the Post Model
To ensure that users don’t submit empty titles or content, you can add validation to the Post model. Open app/models/post.rb
and add the following:
class Post < ApplicationRecord
validates :title, presence: true
validates :content, presence: true
end
This ensures that both the title and content fields must be filled before a post can be saved.
Step 7: Deploying the Application
To deploy your Rails application, you can use a platform like Heroku. First, install the Heroku CLI and log in:
heroku login
Next, create a new Heroku app and push your code:
heroku create
git push heroku master
Run the database migrations on Heroku:
heroku run rails db:migrate
Now, your CRUD application is live!
Conclusion
Building a CRUD application with Ruby on Rails is incredibly fast and straightforward thanks to the scaffold generator. This post covered setting up a simple blog-style application with full create, read, update, and delete functionality. You can further customize and expand this app to suit more complex needs, like adding authentication, file uploads, or more complex database relationships.