我是rails的新手,我想知道如何为多个fields_for
设置不同的标签或占位符,我的表单工作正常,但我想改变它的显示方式。
以下是我的表格:
<%= f.fields_for :lodgedetails do |c| %>
<%= c.text_field :contact, :placeholder => 'Contact1', :class => 'form-control lodge_form' %>
<%= c.text_field :email, :placeholder => 'Email1', :class => 'form-control lodge_form' %>
<% end %>
在控制器中我有:
2.times {@lodge.lodgedetails.build }
现在表单显示为:
我希望它是:
我如何实现上述目标?
答案 0 :(得分:0)
您可以尝试使用each.with_index
来实现此目标:
<% @lodge.lodgedetails.each.with_index do |lodge_detail, index| %>
<%= f.fields_for :lodgedetails, lodge_detail do |c| %>
<%= c.text_field :contact, :placeholder => "Contact#{index}", :class => 'form-control lodge_form' %>
<%= c.text_field :email, :placeholder => "Email#{index}", :class => 'form-control lodge_form' %>
<% end %>
<% end %>
上面的内容将为您提供包含循环中lodgedetails
的当前索引的占位符元素。
答案 1 :(得分:0)
你可以尝试一下:
<% @lodge.lodgedetails.each.with_index do |lodge_detail, ind| %>
<%= f.fields_for :lodgedetails, lodge_detail do |c| %>
<%= c.text_field :contact, :placeholder => "Contact#{ind}", :class => 'form-control lodge_form' %>
<%= c.text_field :email, :placeholder => "Email#{ind}", :class => 'form-control lodge_form' %>
<% end %>
<% end %>
但是当你尝试它时,索引值将从零开始,因此你必须加1,或者你可以为它获取一个本地实例并给它起始值。