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

痴心易碎 提交于 2019-12-10 12:45:33

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/7704973/getting-a-form-to-use-method-delete-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!