Setting Up Modification Queries - Update, Delete
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:
- Add functionality to update an existing
ToDoitem. - Implement the ability to delete
ToDoitems.
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:
-
editmethod: This method retrieves theToDoitem that needs to be edited. It does so by callingTodoService.get_by_id, passing in theidfrom the parameters, and assigns it to the instance variable@todo. -
updatemethod: This method updates theToDoitem. It callsTodoService.update, providing theidand the permitted parameters fromtodo_params. If the update is successful (todois truthy), it redirects to the show page of the updatedToDo. If the update fails, it re-renders the edit form, returning anunprocessable_entitystatus. -
todo_paramsmethod: This private method uses strong parameters to control which attributes can be updated. It requires the parameters to have atodoobject and permits only thetitleanddescriptionattributes. -
TodoService.updatemethod: Finds aToDoitem by itsidand updates it with the provided parameters. It returns the updatedtodoobject if successful, otherwisefalse.
In the form view (app/views/todos/edit.html.erb), we'll create a form for users to edit their existing ToDo items:
Explanation:
-
form_with: Generates a form for theToDoitem usingform_with. It sets the method toputto represent an update action and scopes it to thetodoobject. -
Form elements: The form contains a labeled text field for the
titleand a text area for thedescription, pre-filled with the current values using@todo. -
Submit button: The form includes a submit button labeled "Update" that will send the updated data when clicked.
-
Delete link: A link is provided to allow users to delete the
ToDoitem directly from the edit page, with a JavaScript confirmation dialog.
