creating-a-crud-application-with-ruby-on-rails-and-postgresql.html

Creating a CRUD Application with Ruby on Rails and PostgreSQL

Creating a CRUD (Create, Read, Update, Delete) application is a quintessential skill for any web developer. Among various frameworks, Ruby on Rails (often simply referred to as Rails) stands out for its elegance and productivity. In this article, we will explore how to build a simple CRUD application using Ruby on Rails and PostgreSQL as the database. By the end, you’ll have a fully functional app and a solid understanding of the Rails framework.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete, which are the four fundamental operations of persistent storage. These operations allow users to interact with the data stored in a database, making CRUD applications essential in a variety of fields, such as:

  • Inventory Management: Keeping track of products.
  • Blogging Platforms: Managing posts and comments.
  • User Management Systems: Handling user accounts and profiles.

Setting Up Your Development Environment

Before diving into coding, ensure you have the necessary tools installed:

  1. Ruby: Version 3.0 or higher is recommended.
  2. Rails: The latest version of Rails. Install it using: bash gem install rails
  3. PostgreSQL: Make sure you have PostgreSQL installed and running on your machine.
  4. Node.js and Yarn: For managing JavaScript dependencies.

Once you have these installed, you can create a new Rails application.

Step 1: Creating a New Rails Application

Open your terminal and run the following command to create a new Rails application called crud_app with PostgreSQL as the database:

rails new crud_app --database=postgresql

Change into the application directory:

cd crud_app

Step 2: Configure Database Settings

Open the config/database.yml file and set your database configuration. Ensure the username and password match your PostgreSQL setup:

default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5
  username: your_username
  password: your_password

development:
  <<: *default
  database: crud_app_development

test:
  <<: *default
  database: crud_app_test

production:
  <<: *default
  database: crud_app_production
  username: crud_app
  password: <%= ENV['CRUD_APP_DATABASE_PASSWORD'] %>

Step 3: Create the Model

For this example, let’s create a simple application to manage books. Generate a Book model with the following command:

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

This command will create the model file, migration file, and test file.

Step 4: Run Migrations

Next, apply the migration to create the books table in the database:

rails db:migrate

Step 5: Setting Up the Controller

Generate a controller for Books:

rails generate controller Books

Open the generated file app/controllers/books_controller.rb and add the following code to handle CRUD actions:

class BooksController < ApplicationController
  def index
    @books = Book.all
  end

  def show
    @book = Book.find(params[:id])
  end

  def new
    @book = Book.new
  end

  def create
    @book = Book.new(book_params)
    if @book.save
      redirect_to @book, notice: 'Book was successfully created.'
    else
      render :new
    end
  end

  def edit
    @book = Book.find(params[:id])
  end

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

  def destroy
    @book = Book.find(params[:id])
    @book.destroy
    redirect_to books_url, notice: 'Book was successfully deleted.'
  end

  private

  def book_params
    params.require(:book).permit(:title, :author, :description)
  end
end

Step 6: Setting Up Routes

Open the config/routes.rb file and add the following code to create resourceful routes for the books resource:

Rails.application.routes.draw do
  resources :books
  root 'books#index'
end

Step 7: Creating Views

Next, let’s create the views for our CRUD operations. In app/views/books, create the following files:

  1. index.html.erb: Display all books. ```erb

    Books

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

    <% @books.each do |book| %>
  • <%= link_to book.title, book %> <%= link_to 'Edit', edit_book_path(book) %> <%= link_to 'Destroy', book, method: :delete, data: { confirm: 'Are you sure?' } %>
  • <% end %>

```

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

    <%= @book.title %>

Author: <%= @book.author %>

Description: <%= @book.description %>

<%= link_to 'Edit', edit_book_path(@book) %> <%= link_to 'Back', books_path %> ```

  1. new.html.erb and edit.html.erb: Form for creating and editing books. ```erb

    <%= @book.new_record? ? 'New Book' : 'Edit Book' %>

<%= form_with(model: @book, local: true) do |form| %> <% if @book.errors.any? %>

<%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:

    <% @book.errors.full_messages.each do |message| %>
  • <%= message %>
  • <% end %>
<% end %>

 <div>
   <%= form.label :title %>
   <%= form.text_field :title %>
 </div>

 <div>
   <%= form.label :author %>
   <%= form.text_field :author %>
 </div>

 <div>
   <%= form.label :description %>
   <%= form.text_area :description %>
 </div>

 <div>
   <%= form.submit %>
 </div>

<% end %> <%= link_to 'Back', books_path %> ```

Step 8: Start the Server

You can now start your Rails server to see your CRUD application in action:

rails server

Visit http://localhost:3000 in your web browser, and you should see your CRUD application for managing books.

Troubleshooting Common Issues

  • Database Connection Issues: Ensure your PostgreSQL service is running and your database configurations are correct.
  • Routing Errors: Double-check your routes in config/routes.rb to ensure they are correctly defined.
  • Form Submission Errors: Make sure your strong parameters in the controller are correctly set up.

Conclusion

Congratulations! You've successfully created a CRUD application using Ruby on Rails and PostgreSQL. This foundational project not only demonstrates the power of Rails but also equips you with the skills to build more complex applications. Experiment with adding features like user authentication or pagination to further enhance your app. 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.