John Bachir
John Bachir

Reputation: 22751

Delete multiple objects in Rails with a RESTful controller?

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?

Upvotes: 5

Views: 3122

Answers (3)

BvuRVKyUVlViVIc7
BvuRVKyUVlViVIc7

Reputation: 11821

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 %>

Upvotes: 2

yfeldblum
yfeldblum

Reputation: 65455

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.

Upvotes: -1

cam
cam

Reputation: 14222

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

Upvotes: 3

Related Questions