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?
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With