Getting a form to use :method => :delete (rails)

14,251

Mark Needham has a blog post that talks about why :method => delete in form_for doesn't work. He says

It turns out that ‘form_for’ expects the ‘:method’ to be provided as part of the right hand most argument as part of a hash with the key ‘:html’.

So you need to change your code from:

<%= form_for(line_item, :method => :delete, :remote => true) do |f| %>

to:

<%= form_for(line_item, :html => { :method => :delete, :remote => true }) do |f| %>

I tried it in a Rails 3.0 application, and the generated HTML was:

<input type="hidden" value="delete" name="_method">
Share:
14,251
jyli7
Author by

jyli7

Updated on July 19, 2022

Comments

  • jyli7
    jyli7 almost 2 years

    I have a cart which contains many line_items. I'd like to have a "delete" button next to each line item that, upon clicked, removes the line_item from the cart.

    I know I can do this with a button_to method, but I'd like to use form_for because I'd like to change the attributes of the line_item's parent object at the same time (each line_item also belongs to a course, and I'd like to tell the course parent that it's no longer in the cart).

    Here's my code using form_for:

    <%= form_for(line_item, :method => :delete, :remote => true) do |f| %>
    <%= f.submit :value => "Delete" %>
    <% end %>
    

    The ruby documentation says that simply adding :method => :delete should work (http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for), but the rendered html isn't quite right. It's still

    <input name="_method" type="hidden" value="put">
    

    But it should be:

    <input name="_method" type="hidden" value="delete">
    

    What am I doing wrong?