1

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.

4

1 回答 1

1

我在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

看起来我们可以很好地利用它们,但是它们都是私有方法。我认为另一种解决方案是实现一些这样的辅助方法。

于 2013-02-28T07:19:56.800 回答