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

前端 未结 8 903
無奈伤痛
無奈伤痛 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:48

    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 
    

提交回复
热议问题