在控制器中添加自定义操作并调用它

时间:2014-10-04 15:02:56

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

我想添加这样的动作:

  def destroy_all
    Task.destroy_all
  end

我尝试在视图中链接到此方法:

<%= link_to "delete all", controller: 'tasks', action: 'destroy_all' %>

我添加到我的routes.rb:

resources :tasks

但是当我转到root_path时,我得到了:

No route matches {:action=>"destroy_all", :controller=>"tasks"}

但我有线资源:任务。所以我不知道出了什么问题。 我只想尽可能简单地调用我的destroy_all操作并返回到根路径。

1 个答案:

答案 0 :(得分:2)

resources :tasks没有提供&#39; destroy_all&#39;的路线。您可以使用rake查看所有可用路线:

$ 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

同样,您可以使用rake检查新路线:

    delete_all_tasks DELETE /tasks/delete_all(.:format)    tasks#delete_all