Hi Jay,

I've just run into exactly the same problem, as I'm using jQuery to
build autocompleters and need the generated field id for my
observe_field call. I've looked all over for a way to access the
index, but couldn't find it anywhere. I decided to delve into the
Rails code and found a couple of helper methods in the
InstanceTagMethods moduke (http://github.com/rails/rails/blob/master/
actionpack/lib/action_view/helpers/form_helper.rb).

The methods of interest are santized_object_name and
sanitized_method_name. They take the FormHelper's object_name (which
is publically accessible) and return the generated form element id
(e.g. person[attributes][0][name] becomes person_attributes_0_name).
However, these methods are private to InstanceTagMethods, so you can't
get at them from within your fields_for block.

The solution I've used is to duplicate these methods in my
application_helper.rb, and call them from within my fields_for block:

# app/helpers/application_helper.rb
def sanitized_object_name(object_name)
  object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/,"_").sub(/_$/,"")
end

def sanitized_method_nam(method_name)
  method_name.sub(/\?$/, "")
end

def form_tag_id(object_name, method_name)
  "#{sanitized_object_name(object_name.to_s)}_#{sanitized_method_name
(method_name.to_s)}"
end

Then in my fields_for partial:

# app/views/people/_person_attributes.rb
# wrapped in person_form,fields_for :attributes do |attributes_form|
  <%= f.text_field :name %>
  <%= observe_field form_tag_id(f.object_name, :name), ... %>

This code works for index partials (i.e. those with absolute indexes)
and those generated with timestamp indexes (I'm using a customised
version of Ryan Bates' latest nested form code for Rails 2.3 -
http://github.com/ryanb/complex-form-examples). I'll post this code on
my site aswell.

Hope this helps! If anyone knows a better way to access the form
builder's index, please follow up this post!

Regards,
Chris
--
http://www.chrisblunt.com
http://twitter.com/cblunt

On Aug 17, 10:24 pm, Jay <[email protected]> wrote:
> I'm trying to observe a field that get generated inside a fields_for
> loop (I'm trying to create the form dynamically depending on a
> selection value).  Is there a way to access the index in the field_for
> loop?
>
> Thanks,
> Jay
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to