I'd like to delete multiple objects of the same type using a RESTful controller.
The most simple thing I can think of is to have the destroy action expect a comma-separated list of ids of objects to destroy.
Is there a more elegant way to do this?
I think it would be more elegant to take an array of ids:
http://guides.rubyonrails.org/action_controller_overview.html#hash-and-array-parameters
You could use nested forms for it..
See http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
I think thats the most elegant version...
<% form_for @person do |person_form| %>
<%= person_form.label :name %>
<%= person_form.text_field :name %>
<% person_form.fields_for :children do |child_form| %>
<%= child_form.label :name %>
<%= child_form.text_field :name %>
<% unless child_form.object.new_record? %>
<%= child_form.check_box '_delete' %>
<%= child_form.label '_delete', 'Remove' %>
<% end %>
<% end %>
<%= submit_tag %>
<% end %>
Here's how the RESTful request might look.
POST /posts/delete_multiple HTTP/1.1
Host: www.example.com
post_ids[]=33&post_ids[]=47&post_ids[]=88
Note that while GET, PUT, and DELETE have very specific meanings in the context of REST, POST is more vague and essentially means to take some action. The action to take is given in the URL and additional data specific to the action are passed in the entity (body) of the request. Only use POST in this manner when GET, PUT, and DELETE do not have the intended meaning.
POST is commonly interpreted as "create", but this is not really correct. We commonly use POST for creating new resources when the client doesn't know what the URL of the newly created resource should be. But when the client does get to determine the URL of the newly created resource, the correct verb would be PUT.
POST /posts/batch_deletes with the same entity-body. The sub-resource (a Post::BatchDelete resource) would be created, but would then be immediately run behind-the-scenes and destroyed instantaneously. The effect of running the sub-resource is that all of the posts listed in that sub-resource are also destroyed.