[英]Get input name from Rails form builder
How can I get a string with form input name?如何获取带有表单输入名称的字符串?
<%= form_with model: @post do |f| %>
<%= f.text_field :name %>
<!-- Will produce HTML <input type="text" id="post_name" name="post[name]" value="" /> -->
<% end %>
The question is how can I get the name of input name without generating it?问题是如何在不生成输入名称的情况下获取输入名称的名称? Is this example it should be a string "post[name]"这个例子是否应该是一个字符串“post[name]”
What you could be looking for is the object_name
method您可能正在寻找的是object_name
方法
f.object_name
should return "post"
f.object_name
应该返回"post"
It will work as well for multiple nested fields_for
它也适用于多个嵌套fields_for
<%= form_with model: @team do |team| %>
<%= team.fields_for :players do |player| %>
<%# for 1st player: player.object_name #=> "team[players_attributes][0]" %>
<% end %>
What ever you case is, you still have to concatenate your field name between brackets "[field_name]"
, and so you can easily construct the right name for your input's field无论您遇到什么情况,您仍然必须在括号"[field_name]"
之间连接您的字段名称,因此您可以轻松地为您的输入字段构建正确的名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.