你如何获得一个表单元素的Ruby on Rails生成的id在JavaScript中引用?

问题描述:

使用 form_for 助手和 text_field 调用时,Ruby on Rails将为< input /> 元素。

When using the form_for helper and a text_field call, Ruby on Rails will generate a unique id for the <input /> element that it outputs. How can I generate the same id for later inclusion into JavaScript generated later?

<%= form_for @user do |f| %>
  <%= f.text_field :username %>
<% end %>

然后在页面后面:

Then later in the page:

<%= javascript_tag do %>
  $('<%= id of the :username field %>').doSomethingReallyCool();
<% end %>


我最终创建了一个自定义表单生成器来公开直接属性

I ended up creating a custom form builder to expose the property directly

class FormBuilder < ActionView::Helpers::FormBuilder
  def id_for(method, options={})
   InstanceTag.new( object_name, method, self, object ) \
               .id_for( options )               
  end
end

class InstanceTag < ActionView::Helpers::InstanceTag
  def id_for( options )
    add_default_name_and_id(options)
    options['id']
  end
end

然后设置默认表单生成器

Then set the default form builder

ActionView::Base.default_form_builder = FormBuilder