Is there a method (or way to pull off similar functionality) to do a fields_for_with_index
?
Example:
<% f.fields_for_with_index :questions do |builder, index| %>
<%= render 'some_form', :f => builder, :i => index %>
<% end %>
That partial being rendered needs to know what the current index is in the fields_for
loop.
Checkout Rendering a collection of partials. If your requirement is that a template needs to iterate over an array and render a sub template for each of the elements.
This will render “_children.erb“ and pass the local variable 'children' to the template for display. An iteration counter will automatically be made available to the template with a name of the form
partial_name_counter
. In the case of the example above, the template would be fedchildren_counter
.Hope this helps.
If you want to have control over the indexes check out the
index
optionThis will produce
If the form is submitted, params will include something like
I had to use the index option to get my multi-dropdowns to work. Good luck.
I can't see a decent way to do this through the ways provided by Rails, at least not in -v3.2.14
@Sheharyar Naseer makes reference to the options hash which can be used to solve the problem but not as far as I can see in the way he seems to suggest.
I did this =>
or
In my case
g.object_name
returns a string like this"gallery_set[blog_posts_attributes][2]"
for the third field rendered so I just match the index in that string and use it.Actually a cooler (and maybe cleaner?) way to do it is to pass a lambda and call it to increment.
And the in the view
This would actually be a better approach, following Rails documentation more closely:
From: http://railsapi.com/doc/rails-v3.0.4/classes/ActionView/Helpers/FormHelper.html#M006456
As of Rails 4.0.2, an index is now included in the FormBuilder object:
http://apidock.com/rails/v4.0.2/ActionView/Helpers/FormHelper/fields_for
For example:
I know that this is a bit late but I recently had to do this you can get the index of the fields_for like this
I hope that this helps :)