通过 Rails 中的 link_to 更新字段 [英] Update field through link_to in Rails

查看:47
本文介绍了通过 Rails 中的 link_to 更新字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a tree of products in Rails 3.2 and would like to have an add/remove feature so that users can add new children products or remove existing children for a product. I use the ancestry gem to generate the tree, for a Product 1 it might look like this:

Product 1
add | remove
    Product 2
    add | remove
        Product 3
        add | remove

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

In a partial _product.html.erb I have added Add and Remove links, which works for the add feature, but I cannot get the remove link to work:

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

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

I would like to update the parent_id to nil for the product to be removed when "Remove" is clicked, but the above link_to doesn't seem to be working. I get an: No route matches [POST] "/products/1/edit" routing error. In my product_controller I have:

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

我做错了什么?

我尝试使用 method: put 代替:

<%= link_to "Remove", {parent_id: nil}, method: :put %>

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

then I get a No route matches [PUT] "/products/1/edit" error instead when clicking on the link.

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

I can now change/remove the parent using a form, not at all what I want but anyway:

<%= form_for @product do |f| %>    
    <%= f.label :parent_id %>
    <%= f.text_field :parent_id %>
    <%= f.submit "Update", class: "btn" %>  
<% end %>

是否可以自动将 parent_id: nil 传递到表单中,以便当您点击更新时,它会设置 parent_id: nil(没有文本字段只是一个按钮)?

Would it be possible to automatically pass the parent_id: nil into the form so that when you hit Update, it sets the parent_id: nil (not having a text field just a button)?

推荐答案

尝试

<%= link_to "Remove", update_products_path(product:{parent_id: nil}), method: :put %>

没有 HTTP-Verb update 你需要的是 put.您可以阅读 Rails 和 HTTP-Verbs这里

There is no HTTP-Verb update what you need is put. You can read about Rails and HTTP-Verbs here

这篇关于通过 Rails 中的 link_to 更新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆