Weihang Jian
Weihang Jian

Reputation: 8705

How to get tag id from a record in form_for?

If we use form_for for a record, all input tags inside the form tag will automatically contain an attribute id with value like id="post_3_title", id="post_3_content".

In my case, I want to get those names to create javascript codes dynamically. I wonder if there is any way to do this. Any ideas?

Thanks for your helping.

Upvotes: 1

Views: 225

Answers (1)

Weihang Jian
Weihang Jian

Reputation: 8705

I found the source code in actionpack-3.2.12/lib/action_view/helpers/form_helper.rb:1218.

    def tag_name_with_index(index)
      "#{@object_name}[#{index}][#{sanitized_method_name}]"
    end

    def tag_id
      "#{sanitized_object_name}_#{sanitized_method_name}"
    end

    def tag_id_with_index(index)
      "#{sanitized_object_name}_#{index}_#{sanitized_method_name}"
    end

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

    def sanitized_method_name
      @sanitized_method_name ||= @method_name.sub(/\?$/,"")
    end

It seems that we can make good use of them, however, they are all private methods. I think another solution is to implement some helper methods like this.

Upvotes: 1

Related Questions