【问题标题】:Rails: Using form_for multiple times (DOM ids)Rails:多次使用 form_for(DOM id)
【发布时间】:2011-06-21 15:34:26
【问题描述】:

我想对同一页面中的同一模型多次使用 form_for 助手。但是输入字段使用相同的 ID 属性(在 HTML 中),因此单击另一个表单中字段的标签将选择第一个表单中的相同输入。

除了通过 :for => "title_#{item.id}" 和 :id => "title_#{item.id}" 手动设置所有属性之外,还有其他解决方案吗?

使用 Rails 3.0.9

【问题讨论】:

    标签: ruby-on-rails form-for


    【解决方案1】:

    您可以使用:namespace => 'some_unique_prefix' 选项。与:index 相比,这不会更改name 属性中使用的值。

    也可以使用数组,例如当您有嵌套表单或碰巧有一些共同字段的不同表单时::namespace => [@product.id, tag.id]:namespace => [:product, @product.id]

    【讨论】:

    • 值得指出的是,这只适用于 Rails 3.2 及更高版本。
    • 也许这不是很明显,但是form_for中要使用:namespace。例如:form_for :user, :url => user_session_path, :html => { :class => 'form-inline' }, :namespace => 'quick' do |f|
    【解决方案2】:

    我自己找到了答案,可以将 :index 选项传递给 form_for。该字符串将用于 id 和属性:

    <%= form_for @person, :index => @person.id do |f| %>
      <%= f.label :name %>
      <%= f.text_field :name %>
      <%= f.submit %>
    <% end %>
    

    会解析

    <form accept-charset="UTF-8" action="/person/11" class="edit_person" id="edit_person_11" method="post">
      <!-- Hidden div for csrf removed -->
    <label for="person_11_name">Name</label> 
    <input id="person_11_name" name="person[11][name]" size="30" type="text" /> 
    <input name="commit" type="submit" value="Update Person" /> 
    </form>
    

    请注意,它也会更改输入的名称。

    【讨论】:

    • 很棒的发现!谢谢! :)
    【解决方案3】:

    我相信你可以添加这个参数:

    :html => { :id => 'id_i_want' }
    

    【讨论】:

    • 这将改变表单本身的 id,而不是输入。
    猜你喜欢
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多