Rails:如何为多个fields_for设置不同的标签

时间:2013-12-23 03:23:47

标签: ruby-on-rails ruby-on-rails-4

我是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 }

现在表单显示为:

  • contact1
  • email1
  • contact1
  • EMAIL1

我希望它是:

  • contact1
  • contact2
  • email1
  • EMAIL2

我如何实现上述目标?

2 个答案:

答案 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,或者你可以为它获取一个本地实例并给它起始值。