Setting Up Creation Query - Create with ToDo Item Form

Introduction to Creating ToDo Items

Welcome back! So far, we've learned how to retrieve ToDo items using GET queries. Now, it's time to make our application more interactive by allowing users to create new ToDo items. This lesson will focus on setting up the creation queries and building a form for users to input their ToDo items.

Creating ToDo items is a fundamental feature for our application. Imagine an app where you can see tasks but can't add new ones — it wouldn't be very useful! By the end of this lesson, you'll have significantly enhanced your app's functionality by enabling users to add new tasks.

Key Concepts

In this lesson, we will cover the following key concepts:

  1. Creating a form for adding new ToDo items.
  2. Handling form submissions to save the new ToDo items.
  3. Redirecting users to the details page of the newly created ToDo.

Setting Up the Controller

Let's start with setting up the controller. Open your todos_controller.rb and update it as follows:

class TodosController < ApplicationController
  def new
    @todo = { id: nil, title: '', description: '' }
  end

  def create
    todo = TodoService.create(todo_params)
    redirect_to todo_path(todo[:id])
  end
  
  def show
    @todo = TodoService.find(params[:id]) 
  end

  private

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

Code Explanation

  • new Action: This method initializes a new @todo object with default values (id, title, and description set to nil or empty strings). This is necessary to instantiate the form fields when creating a new ToDo item.

  • create Action: This method is responsible for handling the submission of the new form. It calls a service (TodoService.create) that processes todo_params to create a new ToDo item. After successfully creating a new item, it redirects the user to the details page of the new ToDo by using redirect_to todo_path(todo[:id]).

  • show Action: This method retrieves an existing ToDo item using a service (TodoService.find) and the passed params[:id]. It assigns the found ToDo to @todo for display purposes.

  • todo_params Method: This private method specifies and sanitizes the parameters (:title and :description) required from the form, preventing illegal data from being processed.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal