I have a Rails 2.3.10 app that uses fields_for to include fields on a has_many association's attributes. I'm using accepts_nested_attributes_for on the the parent model and its many children are being shown in the form using:
<% form_for :map do |f| %>
...
<% f.fields_for :markers do |marker_f| %>
<%= marker_f.text_field :lat
<%= marker_f.text_field :long
<% end %>
<% end %>
The fields_for helper iterates over the child marker models and the text_field inputs are generated for each. These text fields have generated id values like:
map_markers_attributes_0_lat and map_markers_attributes_0_long
map_markers_attributes_1_lat and map_markers_attributes_1_long
...
map_markers_attributes_5_lat and map_markers_attributes_5_long
The integer in the id is an index of the records array being iterated over. How do I access this index value for use elsewhere in my code?
For example I want to use Javascript to access the id values on these inputs.
<% form_for :map do |f| %>
...
<% f.fields_for :markers do |marker_f| %>
<%= marker_f.text_field :lat
<%= marker_f.text_field :long
<% content_for :head do %>
<% javascript_tag do %>
$('<%= generate_html_id(marker_f, :lat) %>').observe_field('change');
$('<%= generate_html_id(marker_f, :long) %>').observe_field('change');
<% end %>
<% end %>
<% end %>
<% end %>
I insert some javascript into the head of the html to observe the field for any changes. I need to know the id of the field and my generate_html_id method should be able to replicate the id of the field from the marker_f builder object. However I don't know how to get the index value coming from fields_for.
It seems like there should be a fields_for_with_index method but there is not:
<% form_for :map do |f| %>
...
<% f.fields_for_with_index :markers do |marker_f, i| %>
<%= marker_f.text_field :lat
<%= marker_f.text_field :long
<% content_for :head do %>
<% javascript_tag do %>
$('<%= generate_html_id(marker_f, :lat, i) %>').observe_field('change');
$('<%= generate_html_id(marker_f, :long, i) %>').observe_field('change');
<% end %>
<% end %>
<% end %>
<% end %>
BTW I could create custom id values for the field but would prefer to stick to the conventions.