Topic: fields_for need index of loop

hi,

I need the "counter" for my fields_for loop to plug into a javascript function in the partial.

VIEW:
            <% f.fields_for :trans_products do |builder| %>
                <%= render 'trans_product_fields', :f => builder %>
            <% end %>

f is a transaction, trans_products belongs_to transaction, transaction accepts_nested_attributes_for trans_products.

so in the PARTIAL:

<tr class="fields">
    <td><%= f.text_field :po, :class => 'prodinfo' %></td>
    <td><%= f.text_field :so, :class => 'prodinfo' %></td>
    <td><%= f.text_field :product, :class => 'prodinfo' %></td>
    <td><%= f.text_field :serial, :class => 'prodinfo' %></td>
    <td class=bigprodinfo><%= f.date_select :pos_date, :include_blank => true, :order => [:month, :day, :year] %>
    <%= link_to_function("today", "set_today(#{?????},'pos_date')", :class => "today_link")  %>    </td>
    <td><%= link_to_remove_product "remove", f %></td>           
</tr>

the ???? should read transaction_trans_products_attributes_#number#, #number# shows up correctly for the textfields, the po text field reads id="transaction_trans_products_attributes_0_po" the next trans_product row has id="transaction_trans_products_attributes_1_po"

how can i get this counter value into my link_to_function parameter?

Last edited by gmcc (2010-08-20 16:34:14)

Re: fields_for need index of loop

nested_child_index looks like it might do the job:

<%= link_to_function("today", "set_today(#{f.nested_child_index},'pos_date')", :class => "today_link")  %>
Rob Anderton
TheWebFellas

Re: fields_for need index of loop

Thanks.
I tried your suggestion, it says that the method private...

private method `nested_child_index' called for #<ActionView::Helpers::FormBuilder:0x48fef10>

I have heard you can work around that. I will look into that.

Last edited by gmcc (2010-08-20 23:42:30)

Re: fields_for need index of loop

Turns out that may not be the best idea, when you call the method it increments the counter which will cause problems with your form.

There's a ticket about this here with a patch and a suggested workaround:

f.object_name.gsub(/[^0-9]+/,'')
Rob Anderton
TheWebFellas