rails generic fields_for - 强制子索引

时间:2012-06-01 20:01:09

标签: ruby-on-rails

模型

class Person < AR

end

控制器

def new
  @people = []
  3.times {@people << Person.new)
end

查看

=form_tag :people_form do
 -@people.each_with_index do |person, i|
   =fields_for :person, person do |person_fields|
    =person_fields.text_field :name

很明显,这会为每个人生成相同的html(name = people_form [person] [name])。有没有办法可以让它插入索引,以便每个人都是唯一的? (没有javacript hack)。

例如,如果我能让它生成这样的东西会很好:

<input name='people_form[0][name]' />
<input name='people_form[1][name]' />

1 个答案:

答案 0 :(得分:0)

比你想象的更简单

=form_tag :people_form do
 -@people.each_with_index do |person, i|
   =fields_for "people_form[#{i}]", person do |person_fields|
    =person_fields.text_field :name