问题描述
如何使用 Rails 中的按钮或链接将对象的字段设置为固定值?看起来这应该是一个相当基本的程序,但我没有成功.一个例子是将产品模型的 parent_id 设置为 nil(相关的早期问题 通过 Rails 中的 link_to 更新字段).我设法通过将文本字段留空的表单来实现此目的:
How can I set a field of an object to a fixed value using a button or link in Rails? It seems like this should be a fairly basic procedure, but I haven't been successful with it. An example would be to set the parent_id of a product model to nil (related earlier question Update field through link_to in Rails). I have managed to achieve this through a form by leaving the text field empty:
<%= 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,但这不起作用.
But how can this be done without a text field, simply using a button, so that the parent_id is set to nil when the button is pressed? I have also tried to set the parent_id in a hidden field, but that doesn't work.
<%= form_for @product do |f| %>
<%= f.hidden_field parent_id: nil %>
<%= f.submit "Remove", class: "btn" %>
<% end %>
用于编辑/更新操作的控制器如下所示.
The controller looks like this for the edit/update actions.
products_controller.rb
def edit
@product = Product.find_by_id(params[:id])
end
def update
if @product.update_attributes(params[:product])
flash[:success] = "Product updated"
redirect_to @product
else
render 'edit'
end
end
编辑
请参阅通过 Rails 中的 link_to 更新字段了解如何操作这使用 link_to 而不是表单.
See Update field through link_to in Rails for how to do this using link_to instead of a form.
推荐答案
尝试
<%= f.hidden_field :parent_id, value: nil %>
代替
<%= f.hidden_field parent_id: nil %>
并确保 parent_id
在模型的 attr_accessible
列表中.
And make sure parent_id
is in attr_accessible
list of the model.
这篇关于使用按钮/链接将固定值传递给字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!