Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Rails : retrieve form input field's id

I'm new to Ruby and to Ruby on Rails. I'm trying to find a way to get the id used on an input field created by the hidden_field helper because I need to add some javascript which uses jquery to get the input field by id.

I have two models > Person and Address. Person has_one Address and address has a zip_code property.

I'm using the following code to generate a form with hidden fields:

<%= form.fields_for :address do |form| %>

     <%= form.hidden_field :zip_code %>

<% end %>

this generates the following html:

<input class="text" id="person_address_attributes_zip_code" name="person[address_attributes][zip_code]" type="hidden" />

Is there any method or helper which gives me the id used for the field of a given property? For example, I need to know that for :zip_code the generated id was "person_address_attributes_zip_code".

Many thanks in advance. Bruno

like image 806
Bruno Avatar asked Dec 27 '10 00:12

Bruno


2 Answers

The form builder has access to the object name, which you could use to get at the generated id, given that you know the field name. I tested this in Rails 3:

<%= form.fields_for :addresses do |form|%>  
  <%= "#{form.object_name}[zip_code]".gsub(/(\])?\[/, "_").chop %>
  <%= form.text_field :zip_code %>  
<% end %>
like image 101
Dan Garland Avatar answered Nov 04 '22 02:11

Dan Garland


The easiest way would be to force the id to be whatever you want, for example:

<%= form.hidden_field :zip_code, :id => 'zip_code' %>

The name field is used in the request parameters so it doesn't matter what the id field is set to.

The methods for determining the id in Rails 3 are in actionpack/lib/action_view/helpers/form_helper.rb, mostly in the InstanceTag module. Most are variations on the main model name sanitized to remove special characters followed by underscore followed by the field name sanitized, but nested models and attributes add additional complexity.

like image 1
Brian Deterling Avatar answered Nov 04 '22 02:11

Brian Deterling