How do you get the Ruby on Rails generated id of a form element for reference in JavaScript?

前端 未结 8 905
無奈伤痛
無奈伤痛 2021-02-05 01:01

When using the form_for helper and a text_field call, Ruby on Rails will generate a unique id for the element that it outp

8条回答
  •  情深已故
    2021-02-05 01:39

    In case someone has a FormBuilder object from a fields_for block, it is possible to get its id using this snippet:

    <%= form.fields_for :something do |fields_form| %>
      <%= fields_form.object_name.gsub(/[\[\]]+/, '_').chop %>id
    <% end %>
    

    FieldsForm#object_name returns the field's ID as something like this: user[address][0]. Next, the regex substitution changes groups of one or more brackets to underscores. This substitution leaves a trailing underscore, to which it appends the letters id. For the example provided before, this results in user_address_0_id.

提交回复
热议问题