Community for developers to learn, share their programming knowledge. Register!
Create First Ruby on Rails Project

Creating a To-Do List Application with Ruby on Rails


In this article, you can get training on building a To-Do List Application using Ruby on Rails. This guide is tailored for developers who have a decent understanding of Ruby and the Rails framework. We'll walk through the entire process, from setting up your development environment to deploying your application. By the end, you'll not only have a functional to-do list application but also a deeper understanding of the Rails framework.

Setting Up Your Development Environment

Before diving into the code, we need to ensure that your development environment is properly set up.

Install Ruby and Rails: Make sure you have the latest version of Ruby installed. You can check your Ruby version by running ruby -v in your terminal. If you don't have it installed, you can download it from the official Ruby website. To install Rails, simply run:

gem install rails

Database Setup: For this application, we'll use SQLite as our database. It's lightweight and perfect for development purposes. You can install SQLite by following the instructions on the official SQLite page.

IDE and Tools: Choose your favorite IDE or code editor. Popular options include Visual Studio Code, RubyMine, and Atom. Make sure to have Git installed for version control.

By following these steps, you'll have a solid foundation for developing your Rails application.

Creating a New Rails Application

Now that your environment is ready, let’s create a new Rails application. Open your terminal and run the following command:

rails new todo_list_app

This command creates a new directory called todo_list_app with all the necessary files and structure for a Rails application. Navigate into your application directory:

cd todo_list_app

Generating the To-Do Model

In Rails, models are representations of your data. To create a To-Do model, we can use the Rails generator. Run the following command:

rails generate model Todo title:string completed:boolean

This command generates a model named Todo with a title attribute (string) and a completed attribute (boolean). Rails will also create a migration file for us, which we will use to set up the database schema.

Setting Up the Database

Now that we've defined our model, it’s time to set up the database. First, we need to run the migration to create the todos table in the database. Execute the following command:

rails db:migrate

To verify that the database was set up correctly, open the Rails console:

rails console

And check if the Todo model is working:

Todo.new

If it returns a new Todo object, you’re all set!

Building the To-Do Controller

Controllers in Rails are responsible for handling the logic of your application. Let’s create a TodosController by running the following command:

rails generate controller Todos

This command generates a controller file located at app/controllers/todos_controller.rb. Open this file and implement the basic CRUD actions:

class TodosController < ApplicationController
  def index
    @todos = Todo.all
  end

  def new
    @todo = Todo.new
  end

  def create
    @todo = Todo.new(todo_params)
    if @todo.save
      redirect_to todos_path, notice: "To-Do was successfully created."
    else
      render :new
    end
  end

  private

  def todo_params
    params.require(:todo).permit(:title, :completed)
  end
end

In this code, we define actions for listing (index), creating new (new and create), and handling form submissions.

Creating Views for To-Do Items

Now that we have our controller set up, let's create some views. In Rails, views are stored in the app/views directory. Create a new folder named todos within app/views, and then create the following files:

  • index.html.erb: This file will display all the to-do items.
<h1>To-Do List</h1>
<%= link_to 'New To-Do', new_todo_path %>
<ul>
  <% @todos.each do |todo| %>
    <li><%= todo.title %> - <%= todo.completed ? 'Completed' : 'Pending' %></li>
  <% end %>
</ul>
  • new.html.erb: This file will contain the form for creating a new to-do item.
<h1>New To-Do</h1>
<%= form_with model: @todo, local: true do |form| %>
  <div>
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>
  <div>
    <%= form.label :completed %>
    <%= form.check_box :completed %>
  </div>
  <div>
    <%= form.submit 'Create To-Do' %>
  </div>
<% end %>

By creating these views, we provide a simple interface for users to interact with their to-do items.

Adding Routes for Your Application

To connect your controller actions with the views, we need to define routes. Open config/routes.rb and add the following line:

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

This line creates all the necessary RESTful routes for our To-Do application, allowing us to handle standard actions like index, create, and more.

Implementing CRUD Functionality

So far, we’ve implemented the basic structure of our application. But to complete our CRUD functionality, we need to implement the remaining actions in our TodosController.

  • Show action: This action displays a single to-do item.
def show
  @todo = Todo.find(params[:id])
end

Create a corresponding view file show.html.erb in the todos folder:

<h1><%= @todo.title %></h1>
<p>Status: <%= @todo.completed ? 'Completed' : 'Pending' %></p>
<%= link_to 'Edit', edit_todo_path(@todo) %>
<%= link_to 'Back', todos_path %>
  • Edit action: This action allows users to edit existing to-do items.

For this, you need to add the following methods in your controller:

def edit
  @todo = Todo.find(params[:id])
end

def update
  @todo = Todo.find(params[:id])
  if @todo.update(todo_params)
    redirect_to todos_path, notice: "To-Do was successfully updated."
  else
    render :edit
  end
end

And create an edit.html.erb view:

<h1>Edit To-Do</h1>
<%= form_with model: @todo, local: true do |form| %>
  <div>
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>
  <div>
    <%= form.label :completed %>
    <%= form.check_box :completed %>
  </div>
  <div>
    <%= form.submit 'Update To-Do' %>
  </div>
<% end %>
  • Destroy action: Finally, we need to provide functionality to delete a to-do item.
def destroy
  @todo = Todo.find(params[:id])
  @todo.destroy
  redirect_to todos_path, notice: "To-Do was successfully deleted."
end

With these actions implemented, your application is now capable of creating, reading, updating, and deleting to-do items.

Styling Your Application with CSS

While functionality is important, a well-styled application enhances the user experience. You can add some basic CSS to your application by creating a file app/assets/stylesheets/todos.css:

body {
  font-family: Arial, sans-serif;
}

h1 {
  color: #333;
}

ul {
  list-style-type: none;
}

li {
  margin: 10px 0;
}

a {
  text-decoration: none;
  color: blue;
}

You can link this stylesheet in your application layout file located at app/views/layouts/application.html.erb:

<%= stylesheet_link_tag 'todos', media: 'all' %>

Summary

In this article, we've walked through the process of creating a fully functional To-Do List Application using Ruby on Rails. From setting up your development environment to implementing CRUD functionality and styling your application, you now have a solid foundation to build upon.

This project not only enhances your understanding of Rails but also serves as a practical example of how to develop real-world applications. As you continue to explore Rails, consider expanding this application with additional features, such as user authentication or task categorization.

Last Update: 13 Jan, 2025

Topics:
Ruby on Rails