I am trying to delete all task that is linked to logged in user but when I click on delete all button it shows the error
No route matches [POST] "/tasks/destroy_all"
task_controller.rb
class TaskController < ApplicationController
def all_destory
@user = current_user
@user.tasks.destroy_all
redirect_to user_tasks_path
end
end
route.rb
get '/tasks/destroy_all', to: 'task#all_destory', as: :destroy_all
HTML
<% @tasks.each do |task| %>
<%= task.daily_task %>
<%= task.date %>
<% end%>
<%= button_to "delete all", destroy_all_path %>
CodePudding user response:
When destroying records you want to use the DELETE
HTTP verb.
GET requests are saved in the browsers history and should not create, modify or destroy anything on the server.
Typically in Rails you just have a route to destroy a single record. But if DELETE /things/1
deltes a single resource then DELETE /things
should logically destroy the entire collection:
get '/user/tasks', to: 'users/tasks#index', as: :user_tasks
delete '/user/tasks', to: 'users/tasks#destroy_all'
# app/controllers/users/tasks_controller.rb
module Users
class TasksController < ApplicationRecord
before_action :authenticate_user!
# display all the tasks belonging to the currently signed in user
# GET /user/tasks
def index
@tasks = current_user.tasks
end
# destroy all the tasks belonging to the currently signed in user
# DELETE /user/tasks
def destroy_all
@tasks = current_user.tasks
@tasks.destroy_all
redirect_to action: :index
end
private
# You don't need this if your using Devise
def authenticate_user!
unless current_user
redirect_to '/path/to/your/login',
notice: 'Please sign in before continuing'
end
end
end
end
<%= button_to "Delete all", user_tasks_path, method: :delete %>
CodePudding user response:
Your HTTP verb and your route must match. Currently your button is using POST
, but your route accepts GET
. You could change them both to POST
.
post '/tasks/destroy_all', to: 'task#all_destory', as: :destroy_all
This fixes the problem in the question, but it's not ideal. As @max points out, DELETE
would be more communicative of what clicking the button does– delete resources.