How to get the index of children in a nested form

In a Rails 3.2 application, I use Simple Form to create a complex form.

The form / model is accepts_nested_attributes_for , and I need to get the index of the child objects.

Models:

 class Project has_many :tasks accepts_nested_attributes_for :tasks end class Task belongs_to :project end 

The form

 <%= simple_form_for @project do |f| %> <%= f.simple_fields_for :tasks do |builder| %> ## I need to get the index of each object built via builder <% end %> <% end %> 

How to get the index?

+4
source share
2 answers

This seems to be impossible directly through fields_for. Instead, the following approach works.

 <%= simple_form_for @project do |f| %> <% @project.tasks.each.with_index do |task, index| %> <%= f.simple_fields_for :tasks, task do |builder| %> <%= index %> #get the index here!! <% end %> <% end %> <% end %> 
0
source

You can use this:

 <%= simple_form_for @project do |f| %> <%= f.simple_fields_for :tasks do |builder| %> <%= builder.index %> <% end %> <% end %> 
+6
source

Source: https://habr.com/ru/post/1500841/


All Articles