Creating a basic CRUD application with Ruby on Rails

Creating a Basic CRUD Application with Ruby on Rails

Ruby on Rails, often simply referred to as Rails, is a powerful web application framework that enables developers to build robust applications quickly and efficiently. One of the fundamental concepts in web development is CRUD (Create, Read, Update, Delete) operations, which allow users to interact with data. In this article, we will explore how to create a basic CRUD application using Ruby on Rails, walking through each step in detail.

What is CRUD?

CRUD stands for:

  • Create: Adding new data (e.g., creating a new user).
  • Read: Retrieving existing data (e.g., viewing user profiles).
  • Update: Modifying existing data (e.g., editing user information).
  • Delete: Removing data (e.g., deleting a user).

These operations form the backbone of most web applications, making them essential for any developer to understand.

Getting Started with Rails

Before we dive into coding, make sure you have Ruby on Rails installed on your machine. You can check if it's installed by running:

rails -v

If you don’t have Rails installed, you can install it using the following command:

gem install rails

Step 1: Create a New Rails Application

To create a new Rails application, run the following command in your terminal:

rails new crud_app

This command creates a new directory named crud_app with all the necessary files and folders for a Rails application. Navigate into the newly created directory:

cd crud_app

Step 2: Generate a Scaffold

Rails provides a powerful scaffold generator that creates all the necessary files for a CRUD resource with a single command. 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 (app/models/book.rb)
  • A controller (app/controllers/books_controller.rb)
  • Views (app/views/books)
  • Migration file to create the books table

Step 3: Run Migrations

After generating the scaffold, you need to run the migration to create the database table. Execute the following command:

rails db:migrate

This command updates your database schema to include the new books table.

Step 4: Start the Rails Server

Now, you can start your Rails server to test the CRUD application. Run:

rails server

Navigate to http://localhost:3000/books in your web browser. You should see a basic interface for managing books with options to create, view, edit, and delete.

Understanding the Generated Code

Let’s break down some of the critical components generated by the scaffold.

The Model

The Book model is located in app/models/book.rb. It defines the data structure for your books and can include validations. For example:

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

This validation ensures that every book has a title and an author.

The Controller

The controller, found in app/controllers/books_controller.rb, contains the logic for handling requests. Here’s a quick overview of the key actions:

  • Index: Displays a list of all books.
  • Show: Displays a single book.
  • New: Renders a form for creating a new book.
  • Create: Saves the new book to the database.
  • Edit: Renders a form for editing an existing book.
  • Update: Updates the book in the database.
  • Destroy: Deletes the book from the database.

The Views

Rails generates views for each of the controller actions automatically. You can find them in app/views/books/. The views are written in HTML with embedded Ruby (ERB). For example, index.html.erb displays the list of books:

<h1>Books</h1>

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Author</th>
      <th>Description</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @books.each do |book| %>
      <tr>
        <td><%= book.title %></td>
        <td><%= book.author %></td>
        <td><%= book.description %></td>
        <td><%= link_to 'Show', book %></td>
        <td><%= link_to 'Edit', edit_book_path(book) %></td>
        <td><%= link_to 'Destroy', book, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<%= link_to 'New Book', new_book_path %>

Troubleshooting Common Issues

When developing your CRUD application, you may encounter a few common issues:

  • Database Connection Errors: Ensure your database is set up correctly in config/database.yml.
  • Routing Errors: If you get a "Route not found" error, check your config/routes.rb file. Ensure you have the resources defined:

ruby resources :books

  • Validation Errors: If the application doesn’t save a book, check the model validations. Ensure all required fields are filled out in the form.

Conclusion

Creating a basic CRUD application with Ruby on Rails is a straightforward process that introduces you to the framework's powerful features. By following the steps outlined in this article, you now have a functional application to manage books, complete with a user interface, database interactions, and validations.

As you advance, consider exploring additional features such as user authentication, advanced validations, or even integrating front-end frameworks. The possibilities with Ruby on Rails are vast, making it an excellent choice for web development.

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.