As the last step, we will allow the users of our task manager to edit and delete their tasks. Let’s start by adding the corresponding actions in the tasks_controller.rb
file. This is standard Rails, so I won't go too deep here.
class TasksController < ApplicationController
def edit
@task = Task.find(params[:id])
end
def update
@task = Task.find(params[:id])
respond_to do |format|
if @task.update(task_params)
format.html { redirect_to tasks_url, notice: "Task was successfully updated" }
else
format.html { render :edit, status: :unprocessable_entity }
end
end
end
def destroy
@task = Task.find(params[:id])
@task.destroy
redirect_to tasks_url, notice: "Post was successfully deleted."
end
end
The edit
action finds the task that we want to edit, and the corresponding view displays the edit form. Add the edit.html.erb
file in the app/views/tasks
directory with the following code.
<div>
<h1 class="font-bold text-2xl mb-3">Editing Task</h1>
<div id="<%= dom_id @task %>">
<%= render "form", task: @task %>
<%= link_to "Never Mind", tasks_path, class: "btn mb-3 bg-gray-100" %>
</div>
</div>
Finally, add the edit
and delete
buttons next to the task, in the _task.html.erb
file.
<div class="block">
<%= form_with(model: task, class:"text-lg inline-block my-3 w-72") do |form| %>
...
<% end %>
<%= link_to "Edit", edit_task_path(task),
class: "btn bg-gray-100"
%>
<div class="inline-block ml-2">
<%= button_to "Delete", task_path(task),
method: :delete,
class: "btn bg-red-100" %>
</div>
</div>
That’s it. Reload the page, and you should see our buttons to edit and delete the tasks. Clicking the Delete
button should delete that task, without a full page reload.
Clicking the Edit
button should show you the form with the task in it. After making changes, it should redirect you to the home page. Again, without a full page reload. Turbo Drive makes the fetch request, gets the response, and replaces the DOM content.
That’s it. Congratulations, you have just implemented a fully-featured to-do list using Ruby on Rails and Hotwire frameworks.