Skip to content

Instantly share code, notes, and snippets.

@cblunt
Created February 6, 2010 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cblunt/296631 to your computer and use it in GitHub Desktop.
Save cblunt/296631 to your computer and use it in GitHub Desktop.
Small helper to get the generated id of form tags in a Rails fields_for block (http://chrisblunt.com/blog/2009/10/12/rails-getting-the-id-of-form-fields-inside-a-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_name(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
# ==== Usage
# 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), ... %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment