Back to Posts List


fields_for nested attributes - current child index

i created a better version of this fix as a patch for Rails 2.3.x (2-3-stable branch on github)

Recently (2 hours ago) i started working on a complex form for one of our applications, it came to the point where i had to use the current child index in an accepts_nested_attributes_for form packed with javascript ninja maneuvers.

Surprisingly, i didn’t find anyway to do it. ( Another patch is waiting to the next BugMash festival).

Trying to find some ways to access it, i turned to the rails code (always a good idea to have a frozen rails in your vendor/) and tracked down the method that is responsible for rendering the fields_for nested attributes in the ActionView::Helpers::FormBuilder class, surprisingly, again, it was named fields_for_with_nested_attributes

“Way to go, Sherlock”.

A short read indicated that the current child index is determined by either being specified by the developer (:child_index => something in your fields_for options) or by an automatic value (0 and up) assigned by an auto incremented instance variable named nested_child_index.

My first attempt was to access it with the doomsday device, #send and snatch it, but the inevitable failure arrived when the infamous @lifo pointed me to the fact that when accessing the nested_child_index method, i am actually incrementing the index value.

As a last resort i turned to my (seriously neglected) metaprogramming skills to try and add an unobtrusive getter method for the current child index in a fields_for nested attribute block.

i created fields_for_child_index.rb in my config/initializers folder:

Kind of messy i know, and i am sure that there’s a better way to have store the current association name without going into alias_method_chain, but this is working and will work until i’ll create the core patch for that.

Of course, in the meantime, i am open to improvement suggestions, anyway, this is how you use it:

#current_child_index will return the current child index for every element in the fields_for block.

Important note

unless you use it EXACTLY as i said, i can’t assure it’s working.. it’s just a simple bypass until the patch will be ready. use at your own risk.


blog comments powered by Disqus

I Don't have cookies.


Variable Value
{ '' => [ '#rubyonrails', '#railsbridge', '#ruby', '#mootools' ]}

You're seeing this error because I think it is funny.