9

Given the model Album has_many Song and the latter with localized fields such as:

Song#name_en
Song#description_en
Song#name_fr
Song#description_fr
[...]

Due to the frontend design, I can't do one f.simple_fields_for :songs in one place for all the song attributes, but need to split it:

= f.simple_fields_for :songs do
  = render partial: 'song_en_fields', locals: { f: f, locale: :en }
[...]
= f.simple_fields_for :songs do
  = render partial: 'song_fields', locals: { f: f, locale: :fr }
[...]

The resulting fields are indexed with [0], [1] etc as they should, however, the index doesn't restart with 0 on each indvidivual simple_fields_for, but just keeps counting up.

I've checked the source and found an index option in Rails' fields_for, but this just adds an additional index array.

Is there a way to "reset" the auto-increment of the index when simple_fields_for (or fields_for) is invoked multiple times for the same collection?

svoop
  • 3,318
  • 1
  • 23
  • 41

1 Answers1

9

Instead of trying to reset the autoincrement, you could set the index yourself by putting fields_for in a loop and passing child_index: your_index to it.

yoones
  • 2,394
  • 1
  • 16
  • 20
  • Yep, I just came here to post the same solution. `child_index` does seem to be completely undocumented, at least it's not mentioned anywhere [here](http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for). – Thilo Jan 31 '18 at 13:46