Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing on nested form with multiple `fields_for`

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?

like image 724
svoop Avatar asked Feb 17 '17 09:02

svoop


1 Answers

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.

like image 158
yoones Avatar answered Nov 08 '22 04:11

yoones