首页 > 解决方案 > 如何在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

路由.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 %>

标签: ruby-on-railsrubyruby-on-rails-4

解决方案


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

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

推荐阅读