如何在 Ruby on Rails 的 form_for 中使用 hidden_field?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3131982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use hidden_field in a form_for in Ruby on Rails?
提问by ben
I've read this, but I'm new to RoR so I'm having a little trouble understanding it. I'm using a form to create a new request record, and all of the variables that I need to send exist already. Here is the data I need to send (this is in a do loop):
我读过这个,但我是 RoR 的新手,所以我在理解它时有点困难。我正在使用一个表单来创建一个新的请求记录,并且我需要发送的所有变量都已经存在。这是我需要发送的数据(这是在执行循环中):
:user_id => w[:requesteeID]
:requesteeName => current_user.name
:requesteeEmail => current_user.email
:info => e
Here's my form, which works so far, but only send NULL values for everything:
这是我的表单,到目前为止有效,但只为所有内容发送 NULL 值:
<% form_for(:request, :url => requests_path) do |f| %>
<div class="actions">
<%= f.submit e %>
</div>
<% end %>
How do I use hidden_fields to send the data I already have? Thanks for reading.
如何使用 hidden_fields 发送我已有的数据?谢谢阅读。
回答by Salil
Ref hidden_fieldor hidden_field_tag
参考hidden_field或hidden_field_tag
<% form_for(:request, :url => requests_path) do |f| %>
<div class="actions">
<%= f.hidden_field :some_column %>
<%= hidden_field_tag 'selected', 'none' %>
<%= f.submit e %>
</div>
<% end %>
then in controller
然后在控制器中
params[:selected]="none"
params[:request][:some_column] = request.some_column
Note when you used
使用时注意
<%= f.hidden_field :some_column %>
it change to html
它更改为 html
<input type="hidden" id="request_some_column" name="request[some_column]" value="#{@request.some_column}" />
and when you used
当你使用
<%= hidden_field_tag 'selected', 'none' %>
it change to html
它更改为 html
<input id="selected" name="selected" type="hidden" value="none"/>
回答by Bruno Paulino
You can send a custom value as a hidden input for your model like that:
您可以像这样发送自定义值作为模型的隐藏输入:
<%= f.hidden_field :your_model_field_name, value: 12 %>
Where value: 12is just a demo, but you can pass whatever value you need.
Wherevalue: 12只是一个演示,但您可以传递您需要的任何值。

