通过Rails中的link_to更新字段

gra*_*ter 3 ruby ruby-on-rails ruby-on-rails-3

我在Rails 3.2中有一个产品树,并希望有一个添加/删除功能,以便用户可以添加新的子产品或删除产品的现有子项.我使用ancestry gem生成树,对于Product 1,它可能如下所示:

Product 1
add | remove
    Product 2
    add | remove
        Product 3
        add | remove
Run Code Online (Sandbox Code Playgroud)

在部分_product.html.erb中,我添加了添加和删除链接,这些链接适用于添加功能,但我无法使删除链接起作用:

<span><%= product.name.capitalize %></span>
<%= link_to "Add", new_product_path(parent_id: product) %> | 
<%= link_to "Remove", {parent_id: nil}, method: :update %>
Run Code Online (Sandbox Code Playgroud)

我想在单击"删除"时将parent_id更新为nil,以便删除产品,但上面的link_to似乎不起作用.我得到:没有路由匹配[POST]"/ products/1/edit"路由错误.在我的product_controller中,我有:

def update
   if @product.update_attributes(params[:product])
     flash[:success] = "Product updated"
     redirect_to @product
   else
     render 'edit'
  end
end
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

编辑:

我尝试使用method: put:

<%= link_to "Remove", {parent_id: nil}, method: :put %>
Run Code Online (Sandbox Code Playgroud)

然后我No route matches [PUT] "/products/1/edit"点击链接时收到错误.

我现在可以使用表单更改/删除父项,而不是我想要的但是无论如何:

<%= form_for @product do |f| %>    
    <%= f.label :parent_id %>
    <%= f.text_field :parent_id %>
    <%= f.submit "Update", class: "btn" %>  
<% end %>
Run Code Online (Sandbox Code Playgroud)

是否可以自动将parent_id:nil传递给表单,这样当你点击Update时,它会设置parent_id:nil(没有文本字段只是一个按钮)?

kri*_*ard 7

尝试

<%= link_to "Remove", update_products_path(product:{parent_id: nil}), method: :put %>
Run Code Online (Sandbox Code Playgroud)

没有HTTP-Verb update你需要的是什么put.您可以在此处阅读有关Rails和HTTP-Verbs的 信息

  • 可以这样想:`new`使用GET来呈现一个空表单,用于使用POST来创建`和`对象; `edit`使用GET来呈现一个填充了当前数据状态的表单,以便您使用PUT来"更新"对象.`new`和`edit`显示数据,`create`和`update`保存.显示始终使用HTTP GET动词,create使用POST并且更新使用PUT. (2认同)