Adding and Editing ToDo Items

Welcome back! In the previous lessons, you learned how to retrieve and create ToDo items. Now, it's time to make our application even more powerful by adding the ability to update and delete ToDo items. These actions are crucial because they allow users to manage their tasks dynamically, keeping their to-do list accurate and up-to-date.

What You'll Learn

In this lesson, you will:

  1. Add functionality to update an existing ToDo item.
  2. Implement the ability to delete ToDo items.

Both of these features are critical for a fully functional ToDo application. Imagine having a list that you can't edit or update — you would soon find it outdated and not very useful.

Update Functionality

Let's first look at how to add the update feature. Open your todos_controller.rb and add the following methods:

Additionally, update the TodoService to include the update method:

Explanation:

  • edit method: This method retrieves the ToDo item that needs to be edited. It does so by calling TodoService.get_by_id, passing in the id from the parameters, and assigns it to the instance variable @todo.

  • update method: This method updates the ToDo item. It calls TodoService.update, providing the id and the permitted parameters from . If the update is successful ( is truthy), it redirects to the show page of the updated . If the update fails, it re-renders the edit form, returning an status.

Delete Functionality

Deleting a ToDo item is just as important as creating or updating one. Here's how you can enable users to remove tasks that are no longer needed. Add the destroy method to your todos_controller.rb:

Add the delete method to the TodoService:

Explanation:

  • destroy method in the controller: This method deletes the specified ToDo item by calling TodoService.delete with the appropriate id. After deletion, it redirects to the list of all ToDos (todos_path).

  • TodoService.delete method: This method retrieves the item by its and deletes it using the method if it exists. The safe navigation operator is used to ensure that is called only if is not .

Why It Matters

Updating and deleting ToDo items are essential features for any task management application. They provide users with the flexibility to keep their task list current, efficient, and relevant. The ability to modify and clean up a to-do list is what makes an application truly dynamic and user-friendly.

By the end of this lesson, you will have empowered users to interact more meaningfully with your app, making it a valuable tool for everyday task management. Exciting, isn't it? Let's jump into the practice section and bring these features to life!

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