控制器中添加自定义操作,并调用其
问题描述:
我想补充的行动是这样的:控制器中添加自定义操作,并调用其
def destroy_all
Task.destroy_all
end
我尝试连结此方法的观点:
<%= link_to "delete all", controller: 'tasks', action: 'destroy_all' %>
我加入到我的路线.RB:
resources :tasks
但是,当我去我的root_path我得到:
No route matches {:action=>"destroy_all", :controller=>"tasks"}
但我有线资源:任务。所以我不知道什么是错的。 我只想尽可能简单地调用我的destroy_all
操作并返回根路径。
答
resources :tasks
没有提供'destroy_all'的路由。
$ rake routes
你会看到,resources :tasks
带来了一些新的路线:您可以使用耙子查看所有可用路由的
tasks GET /tasks(.:format) tasks#index
POST /tasks(.:format) tasks#create
new_task GET /tasks/new(.:format) tasks#new
edit_task GET /tasks/:id/edit(.:format) tasks#edit
task GET /tasks/:id(.:format) tasks#show
PATCH /tasks/:id(.:format) tasks#update
PUT /tasks/:id(.:format) tasks#update
DELETE /tasks/:id(.:format) tasks#destroy
如果你想添加一个路由,然后delete_all
你可以改变你的资源:
resources :tasks do
collection do
delete :delete_all
end
end
同样,你可以使用耙子来检查新航线:
delete_all_tasks DELETE /tasks/delete_all(.:format) tasks#delete_all
完美。谢谢。但是现在我遇到了以下问题:_'点击'全部删除'后,'TasksController_'找不到操作'show'。我在'destroy_all'动作中使用了'render'index'',并且我尝试了'render nothing:true'。我不想渲染任何特别的,只有根路径。 – Jensky 2014-10-04 15:30:16
很高兴帮助。这听起来像是一个新问题,创建一个新的SO问题可能是一个好主意,以便人们可以看到控制器的操作代码。当你发布新的问题时,我会很乐意回答:) – 2014-10-04 15:35:26
你说得对。再次感谢你 :) – Jensky 2014-10-04 15:38:04