2014-10-04 64 views
1

我想補充的行動是這樣的:控制器中添加自定義操作,並調用其

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操作並返回根路徑。

回答

2

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 
+0

完美。謝謝。但是現在我遇到了以下問題:_'點擊'全部刪除'後,'TasksController_'找不到操作'show'。我在'destroy_all'動作中使用了'render'index'',並且我嘗試了'render nothing:true'。我不想渲染任何特別的,只有根路徑。 – Jensky 2014-10-04 15:30:16

+0

很高興幫助。這聽起來像是一個新問題,創建一個新的SO問題可能是一個好主意,以便人們可以看到控制器的操作代碼。當你發佈新的問題時,我會很樂意回答:) – 2014-10-04 15:35:26

+0

你說得對。再次感謝你 :) – Jensky 2014-10-04 15:38:04