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

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

    I don't really like my own solution that much, but I tried not to go and patch InstanceTag.

    Unfortunately that meant lifting the sanitization code from ActionView::Helpers::InstanceTagMethods

    class MyCoolFormBuilder < ActionView::Helpers::FormBuilder
        def sanitized_object_name
          @sanitized_object_name ||= object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
        end
    
        def field_id_for(method)
          "#{sanitized_object_name}_#{method.to_s.sub(/\?$/,"")}"
        end
    end
    

提交回复
热议问题