简体   繁体   English

从 Rails 表单构建器获取输入名称

[英]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]”

When you are within a form_with model: @post block you could build the "post[name]" string like this:当您在form_with model: @post块中时,您可以像这样构建"post[name]"字符串:

"#{dom_class(f.object)}[name]"

See the docs of dom_class查看dom_class的文档

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.

相关问题 在不使用输入字段的情况下从 Rails 表单构建器获取数据属性值 - Get data attribute value from the Rails form builder without using input field 如何获取Rails表单构建器将为特定字段生成的HTML“名称”属性? - How do I get the HTML 'name' attribute a rails form builder will generate for a certain field? target HTML&#39;name&#39;属性使用Jquery构建Rails表单 - target HTML 'name' attribute a rails form builder with Jquery 从表单中获取 API url 请求的输入? - Get Input from form for API url Request in rails? Rails 3中的自定义表单生成器 - Custom Form Builder in Rails 3 Rails 4:更改简单表单输入的“名称”属性 - Rails 4: Change 'name' attribute of Simple Form input 更改Rails中表单输入的名称和ID - Change the name and id on a form input in rails 如何在rails中的form_builder中获取关系值 - how to get a relationship value in form_builder in rails 当我尝试从 ruby​​ on rails 上的 Form 获取输入时,我得到了简单名称的哈希数组瞬间。 如何解决? - When I tried to get input from the Form on ruby on rails, I am getting back hash array instant of simple name. How to solve it? 使用具有自动递增名称的Rails表单中的输入X创建X数量的新数据库行 - Creating X amount of new database rows using input X from a form in Rails with auto-incrementing name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM