简体   繁体   中英

How do I get the HTML 'name' attribute a rails form builder will generate for a certain field?

When you've got a form field such as this:

<%= f.text_field :last_name %>

it will generate this in HTML:

<input id="person_last_name" name="person[last_name]" size="30" type="text" />

I'd like to know if there's any way to get the name attribute (in this case "person[last_name]") that will be generated.

It seems a bit of an odd thing to want to get but I've got my reasons! I also can't be bothered launching into a lengthy explanation too.

After inspecting the form object, I found that you can get the object_name from it.

So this worked well for me: "#{f.object_name}[field_name]"

Which will generate: object[object_attributes][0][field_name]

Well, as expected, the comment you have is quite true :)

The place in the source where this happens is the InstanceTag class to which all the tag generation drills down. The method is called tag_name .

ActionView::Helpers::InstanceTag.new(
  ActiveModel::Naming.param_key(@object_in_form_for),
  :your_attribute,
  :this_param_is_ignored
).send(:tag_name)

Also there is tag_name_with_index attribute which accepts index as first parameter. Also both tag_name and tag_name_with_index have optional parameter multiple = false , which is used for arrays (just adds [] to the end of the generated name).

Finally, there are similar methods if you need id instead of name - tag_id and tag_id_with_index respectively.

Neutrino's answer is great. Just want to add what I found, may not be exactly right. But it worked for me.

Find below method in action_view/helpers/form_tag_helper.rb

    def sanitized_object_name
      @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
    end

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM