Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 routing - :delete method on :collection

I want to create a route to allow deleting all shares. RESTful way would be to use verb DELETE. How can I create a routing that points to:

DELETE /shares

I tried in the routes:

resources :shares do
  delete :on => :collection
end

But this yielded an error that rails can't turn nil into a symbol.

For now I have:

resources :shares do
  delete 'delete_all', :on => :collection
end

EDIT: I had a typo in controller action name and this latter way works, but produces URL /shares/delete_all which is not very RESTful.

How can I drop the _delete_all_ part?

like image 653
Laas Avatar asked May 24 '11 18:05

Laas


2 Answers

For Rails 3 you can do it this way and have nice resourceful GET/DELETE collection actions pointing to index and delete_all respectively:

resources :shares do
  delete :index, on: :collection, action: :delete_all
end

If you're using Rails 4 you can make use of concerns to DRY this up and apply it to many resources:

concern :deleteallable do
  delete :index, on: :collection, action: :delete_all
end

resources :shares, concerns: :deleteallable
resources :widgets, concerns: :deleteallable
like image 86
MDahlke Avatar answered Oct 12 '22 12:10

MDahlke


What am I missing?

match 'shares', :to => 'shares#delete_all', :via => :delete

more info: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/

<subjective opinion> This is generally a bad idea and a code/design smell. The need to be deleting all records via a RESTful interface should really be behind a protected (authenticated) action and/or the action should be scoped to the user somehow.

like image 41
colinross Avatar answered Oct 12 '22 13:10

colinross