How to create a simple CRUD application in Ruby on Rails

How to Create a Simple CRUD Application in Ruby on Rails

Creating a CRUD (Create, Read, Update, Delete) application is one of the most foundational tasks in software development. It provides a great way to learn the basics of web application development. In this article, we will guide you through the process of building a simple CRUD application using Ruby on Rails. This step-by-step guide will cover everything from setting up your environment to deploying your app.

What is Ruby on Rails?

Ruby on Rails, often simply referred to as Rails, is a powerful web application framework written in the Ruby programming language. It follows the MVC (Model-View-Controller) architecture, which helps in organizing application code. Rails emphasizes convention over configuration, making it quicker to develop applications without extensive setup.

Use Cases for CRUD Applications

CRUD applications are ubiquitous in software development and can be used in various scenarios:

  • Content Management Systems (CMS): Managing blog posts or articles.
  • Inventory Management: Keeping track of products and stock levels.
  • User Management: Handling user profiles and account settings.
  • Task Management: Creating to-do lists or project management tools.

Setting Up Your Environment

Before we dive into coding, ensure that you have Ruby and Rails installed on your machine. You can check your Ruby installation by running:

ruby -v

To install Rails, use the following command:

gem install rails

Step 1: Create a New Rails Application

To create a new Rails application, open your terminal and run:

rails new crud_app
cd crud_app

This command creates a new directory called crud_app with all the necessary files and directories for a Rails application.

Step 2: Generate a Scaffold

Rails offers a powerful scaffolding feature that can quickly generate the necessary files for a CRUD application. Let’s create a simple application for managing books. Run the following command:

rails generate scaffold Book title:string author:string description:text

This command generates:

  • A model (book.rb)
  • A controller (books_controller.rb)
  • Views for each action (index, show, new, edit)
  • Migration files to create the books table in the database

Step 3: Run Migrations

Next, we need to create the database table for our books. Run the migration with:

rails db:migrate

This command applies the migration files and creates the books table with the specified fields.

Step 4: Start the Rails Server

To see your application in action, start the Rails server:

rails server

Now, open your web browser and navigate to http://localhost:3000/books. You should see a basic interface for managing books.

Step 5: Understanding the Code Structure

Models

The model defines the data structure of your application. Open app/models/book.rb and notice how it inherits from ApplicationRecord. You can add validations or methods here as needed.

Controllers

The controller handles the incoming requests and interacts with the models. In app/controllers/books_controller.rb, you will find methods for each CRUD action:

  • index: Displays a list of books.
  • show: Shows a single book.
  • new: Renders a form for creating a new book.
  • create: Saves a new book to the database.
  • edit: Renders a form for editing a book.
  • update: Updates an existing book.
  • destroy: Deletes a book.

Views

The views are responsible for displaying HTML to the user. Each view file is located in the app/views/books directory. You can customize these templates to improve the user interface.

Step 6: Adding Basic Validations

To ensure data integrity, you can add validations to your model. Open app/models/book.rb and modify it as follows:

class Book < ApplicationRecord
  validates :title, presence: true
  validates :author, presence: true
end

This code snippet ensures that both the title and author fields must be present when creating or updating a book.

Step 7: Enhancing User Experience

To improve user experience, consider adding flash messages for actions like successful creation or updates. In your application.html.erb layout file, add the following code snippet:

<% flash.each do |key, message| %>
  <div class="alert alert-<%= key %>"><%= message %></div>
<% end %>

In your controller methods, you can set flash messages like this:

def create
  @book = Book.new(book_params)
  if @book.save
    flash[:notice] = "Book was successfully created."
    redirect_to @book
  else
    render :new
  end
end

Step 8: Testing Your Application

To ensure everything works as expected, you can use the built-in Rails testing framework. Create tests for your model and controller, and run them with:

rails test

Conclusion

Congratulations! You’ve built a simple CRUD application in Ruby on Rails. This project has provided a solid foundation in web application development with Rails. You can now experiment with adding more features, such as user authentication or API endpoints for a more complex application.

By mastering CRUD operations, you can tackle more advanced projects in the future. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.