views:

49

answers:

2

I'm trying to route only an http verb. Say I have a comments resource like so:

map.resources :comments

And would like to be able to destroy all comments by sending a DELETE /comments request. I.e. I want to be able to map just the http verb without the "action name" part of the route. Is this possible?

Cheers

+2  A: 

You could do this:

map.resources :comments, :only => :destroy

which produces a route like the following (you can verify with rake routes)

DELETE /comments/:id(.:format) {:controller=>"comments", :action=>"destroy"}

But note that the RESTful destroy is designed for removing a specific record not all records so this route is still expecting an :id parameter. A hack might be to pass some sentinel value for :id representing "all" in your application context.

On the other hand, if your comments belong to another model, then removing the other model would/should remove the comments too. This is conventionally how multiple row deletes might normally occur.

bjg
The comments resource in this case was just fictional^^ There really should be a way to do this, just as the default 'remove' route does...
Jim Sagevid
+1  A: 

Since this is not standard RESTful action, you will need to use a custom route.

map.connect '/comments', 
  :controller => 'comments',
  :action => "destroy_all",
  :conditions => { :method => :delete }

In your controller:

class CommentsController < ApplicationController
  # your RESTful actions here

  def destroy_all
    # destroy all your comments here
  end
end

In view, invoke like this:

<%= link_to "delete all comments", 
        comments_path,
        :method => :delete, 
        :confirm => "Are you sure" %>

ps. I didn't test this code, but I think it should work.

Aaron Qian
wouldn't this action better be added with just a map.resources :comments, :collection => { :destroy_all => :delete }I get the feeling that just DELETE'ing to the collection resource would be more `RESTful`...Thanks for your reply :)
Jim Sagevid
Using the :collection attribute will generate the URL as /messages/delete_all and according the question is not desirable.
Aaron Qian