Building a simple CRUD application with Ruby on Rails

Building a Simple CRUD Application with Ruby on Rails

Ruby on Rails, often simply referred to as Rails, is a powerful web application framework that emphasizes convention over configuration. If you’re looking to build a simple CRUD (Create, Read, Update, Delete) application, Rails provides an elegant and efficient way to do so. In this article, we’ll walk through the steps to create a basic CRUD application, covering everything from setting up your environment to writing your first lines of code.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete - the four basic operations that you can perform on any data in a database. In the context of web applications, CRUD functionality allows users to interact with data seamlessly. For instance, a blog application might allow users to create new posts (Create), view existing posts (Read), edit posts (Update), and delete posts (Delete).

Use Cases for CRUD Applications

  • Blog Platforms: Users can create, read, update, and delete posts.
  • Inventory Management: Keep track of items, their quantities, and other details.
  • User Management Systems: Administrators can manage user accounts and permissions.
  • Task Management Apps: Users can add, view, modify, and remove tasks.

Setting Up Your Ruby on Rails Environment

Before diving into coding, ensure you have Ruby and Rails installed on your machine. If you don’t have them installed yet, follow these steps:

  1. Install Ruby: Use a version manager like RVM or rbenv to install Ruby. bash curl -sSL https://get.rvm.io | bash -s stable --ruby

  2. Install Rails: Once Ruby is set up, you can install Rails. bash gem install rails

  3. Create a New Rails Application: In your terminal, navigate to the directory where you want to create your app and run: bash rails new crud_app cd crud_app

  4. Set Up Your Database: Rails uses SQLite by default, but you can configure it for other databases like PostgreSQL or MySQL. For now, let’s stick with SQLite. Run: bash rails db:create

Creating the Basic CRUD Application

Step 1: Generate Your Model

Let’s create a simple application to manage articles. Start by generating a model for your articles. This will define the database table.

rails generate model Article title:string content:text

This command creates several files, including a migration file. Migrations are a way to alter your database schema over time.

Step 2: Run the Migration

Now, let’s apply the migration to create the articles table in the database.

rails db:migrate

Step 3: Generate a Controller

Next, generate a controller to handle the CRUD operations.

rails generate controller Articles

Step 4: Define Routes

Open config/routes.rb and set up the routes for your articles.

Rails.application.routes.draw do
  resources :articles
end

This line creates all the necessary routes for CRUD actions.

Step 5: Implement Controller Actions

Open app/controllers/articles_controller.rb and implement the necessary actions:

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article, notice: 'Article was successfully created.'
    else
      render :new
    end
  end

  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
      redirect_to @article, notice: 'Article was successfully updated.'
    else
      render :edit
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to articles_url, notice: 'Article was successfully deleted.'
  end

  private

  def article_params
    params.require(:article).permit(:title, :content)
  end
end

Step 6: Create Views

Now, let’s create views for each action. In app/views/articles/, create the following files:

  1. index.html.erb: List all articles. ```erb

    Articles

<%= link_to 'New Article', new_article_path %>

    <% @articles.each do |article| %>
  • <%= link_to article.title, article %> <%= link_to 'Edit', edit_article_path(article) %> <%= link_to 'Delete', article, method: :delete, data: { confirm: 'Are you sure?' } %>
  • <% end %>

```

  1. new.html.erb and edit.html.erb: Create forms for new and edit actions. ```erb

    <%= action_name.capitalize %> Article

<%= form_with model: @article do |form| %>

<%= form.label :title %> <%= form.text_field :title %>
<%= form.label :content %> <%= form.text_area :content %>
<%= form.submit %>
<% end %> ```

  1. show.html.erb: Display a single article. ```erb

    <%= @article.title %>

<%= @article.content %>

<%= link_to 'Edit', edit_article_path(@article) %> <%= link_to 'Back', articles_path %> ```

Step 7: Start the Server

Finally, start your Rails server:

rails server

Navigate to http://localhost:3000/articles in your web browser to see your CRUD application in action!

Troubleshooting Common Issues

  • Routing Errors: Ensure your routes are correctly defined in routes.rb.
  • Database Migrations: If you change your model, remember to create and run a new migration.
  • Form Submission Issues: Check your strong parameters in the controller to ensure they permit the right fields.

Conclusion

Congratulations! You’ve built a simple CRUD application using Ruby on Rails. This foundational knowledge can be expanded to create more complex applications. As you continue to learn, consider incorporating features like user authentication, file uploads, or even integrating APIs. Rails provides a wealth of tools to help you create powerful web applications efficiently. 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.