【问题标题】:Change html form id generated by form_for rails 3.1更改 form_for rails 3.1 生成的 html 表单 ID
【发布时间】:2011-12-30 17:17:20
【问题描述】:

我有这个form_for:

<%= form_for [post, Comment.new,], :remote => true do |f| %>
<%= f.text_area :content, :cols =>10, :rows => 1%>
<% end %>
<%= f.submit :class => "input_comment"  %>

即生成下一段代码html:

<form method="post" id="new_comment" data-remote="true" class="new_comment" 
action="/post/4efcda9e1d41c82486000077/comments" accept-charset="UTF-8"><div 
style="margin:0;padding:0;display:inline"><input type="hidden" value="✓" name="utf8">
<input type="hidden" value="ctVfDF/O4FIR91I7bC5MVezQmutOCkX3dcXe73uNPZY=" name="authenticity_token">

<textarea rows="1" name="comment[content]" id="comment_content" cols="10"></textarea>
<input type="submit" value="Create Comment" name="commit" class="input_comment">
</form>

如果我在同一页面中有多个表单,则不是具有相同 id 的 html。

  • form_for 生成的 id id="new_comment"
  • textarea 的 id 生成 id="comment_content"

在同一个页面中有这么多表单是无效的 html。

如何从 rails 3.1 更改 form_for 方法助手自动生成的 id?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 form-for


    【解决方案1】:

    根据 miked 所说,为帖子制作唯一表单 ID 的最简单方法是在 id 属性中使用帖子的 ID 编号,如下所示:

    <%= form_for [post, Comment.new,], :remote => true, :html => { :id => "new_comment_on_#{post.id}" } do |f| %>
    

    【讨论】:

    • 对于文本区域或按钮、字段...等,例如:id =&gt; "text_#{post.id}"。
    • 你会做同样的事情,但是对于text_area,在:html =&gt; {} 中传递它是不必要的。如&lt;%= f.text_area :content, :cols =&gt;10, :rows =&gt; 1, :id =&gt; "comment_on_#{post.id}_content" %&gt;。查看文档中的 text_area form helper 以获取 rails。
    【解决方案2】:

    我认为:namespace 选项正是您要找的。​​p>

    它将名称附加到表单的 ID 以及所有输入和标签字段。

    例如

    <%= form_for [post, Comment.new,], namespace: 'NAMESPACE', :remote => true do |f| %>
        <%= f.text_area :content, :cols =>10, :rows => 1%>
    <% end %>
    

    会产生:

    表单 ID = NAMESPACE_new_comment

    文本区域 id = NAMESPACE_comment_content

    来自docs:

    :namespace - 表单的命名空间,以确保 id 的唯一性 表单元素的属性。命名空间属性将作为前缀 在生成的 HTML id 上带有下划线

    【讨论】:

    • 这是正确的答案,Rails 已经包含了命名空间选项,特别是针对这个用例。
    • 我同意。这应该是答案。
    • 谢谢@Subtletree。在某些情况下,id 属性不会因分配而改变。因此,这是最正确的方法。我试过的版本:Rails:6.0.2.2
    【解决方案3】:

    您应该能够将表单的 id 设置为您想要的任何内容。比如:

    <%= form_for @object, :html=> {:id => 'custom_form_id'} do |f| %>
    

    【讨论】:

    • 或 1.9.3 语法:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 2012-02-22
    相关资源
    最近更新 更多