如何在 rails haml 中呈现文本字段

How to render a textfield in rails haml

我想显示带有特定参数的文本字段。当我使用 :

%input{:type=>"text", :name => "search_name",:maxlenght => "200" ,:class => "text_field", :placeholder => t("homepage.save_search.save_field_placeholder") }

一切正常,生成的html是我想要的:

<input class="text_field" maxlenght="200" name="search_name" placeholder="Search name" type="text">

但是当我使用以下语法时:

=text_field :search_name, :maxlenght => "200", :class => "text_field", :placeholder => t("homepage.save_search.save_field_placeholder")

它生成以下 html :

<input type="text" name="search_name[{:maxlenght=>&quot;200&quot;, :class=>&quot;text_field&quot;, :placeholder=>&quot;Search name&quot;}]" id="search_name_{:maxlenght=>&quot;200&quot;, :class=>&quot;text_field&quot;, :placeholder=>&quot;Search name&quot;}">

阅读其他 rails 和 haml 文件生成文本字段的示例,我认为这两个解决方案是等效的。谁能解释一下区别?

在前一行中创建文本字段的地方,后一种语法是处理对象时使用的辅助工具。查看 text_field form helper 方法签名

text_field(object_name, method, options = {}) public

For these helpers the first argument is the name of an instance variable and the second is the name of a method (usually an attribute) to call on that object. Rails will set the value of the input control to the return value of that method for the object and set an appropriate input name. If your controller has defined @person and that person's name is Henry then a form containing:

<%= text_field(:person, :name) %>

将产生类似于

的输出
<input id="person_name" name="person[name]" type="text" value="Henry"/>

source