ruby-on-rails - 如何在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 %>
解决方案
销毁记录时,您要使用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 %>
推荐阅读
- c - 从C中的双链表中删除节点?
- python - 使用循环编写投资 python 代码
- json - Azure 缺少为此存储帐户启用 EncryptionAtRest/客户托管密钥的先决条件
- python - 如何从 Python 中的大字典中创建子字典?
- reactjs - 在 useEffect 返回函数中未定义 Redux 状态变量
- firebase-realtime-database - 发布的 Firebase 安全规则示例不正确
- excel - 如果第 7 列中的一个单元格等于另一个单元格中的值,则更改为另一个单元格中的值
- c++ - C++ 编程,使用 std::vector 构建矩阵
- python - 根据其他列中是否存在值查询列
- cmake - 如何从 cmake 调用 ExternalProject 输出二进制文件?