如何在 rails 中销毁所有链接到登录用户的任务

how can destroy all task linked to login user in rails

我正在尝试删除链接到已登录用户的所有任务,但是当我点击删除所有按钮时它显示错误

 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 %>

您的 HTTP 谓词和路由必须匹配。当前您的按钮使用 POST,但您的路线接受 GET。您可以将它们都更改为 POST.

post '/tasks/destroy_all', to: 'task#all_destory', as: :destroy_all

这解决了问题中的问题,但并不理想。正如@max 指出的那样,DELETE 更能说明单击按钮的作用——删除资源。

DELETE documentation

销毁记录时,您要使用 DELETE HTTP 动词。

GET 请求保存在浏览器历史记录中,不应创建、修改或破坏服务器上的任何内容。

通常在 Rails 中,您只有一条销毁单个记录的途径。但是,如果 DELETE /things/1 删除单个资源,那么 DELETE /things 应该在逻辑上销毁整个集合:

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 %>