0

模型

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])。有没有办法让它插入索引,所以每个人的 for 都是唯一的?(没有 javacript hack)。

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

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

2 回答 2

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
于 2012-06-01T20:15:55.287 回答
0

从 Rails 6 开始,您可以使用该index选项。

fields_for :person, person, index: i do |person_fields|
于 2021-10-29T15:24:13.703 回答