【问题标题】:rails nested form assign unique id to generated fieldrails嵌套表单为生成的字段分配唯一的ID
【发布时间】:2014-11-11 19:53:59
【问题描述】:

我想为嵌套表单生成的每一行分配唯一的 ID。

我看了这个问题Creating unique id for <fieldset> when using form_for Rails Nested Model Form 但这并不能解决我的问题。

【问题讨论】:

    标签: ruby-on-rails nested-forms


    【解决方案1】:

    我通过查看嵌套表单 gem 设法解决了这个问题。 为每个添加动态生成嵌套的 gem 内部唯一 ID。 解析数据蓝图并将“new_#{association}”替换为生成的唯一 ID。在我的情况下,关系就像“目录”has_many“类别”,所以我的关联是类别。 我用 id = "new_categories" 分配了新行,并在添加新行时将其替换为唯一 ID。

    也许它对其他人有用。

    【讨论】:

    • 如何在 rails4 中允许 new_tags?我应该允许吗?
    • 您能否发布代码的链接或更明确的链接?对我不起作用,我对您的解决方案非常感兴趣:)
    • 哦,抱歉,刚刚意识到我使用了错误的关联名称 ^^"。它必须是带有“s”的当前部分 (_association_fields) 的名称,谢谢您的解决方案!
    • @CyrilDD 很高兴它也对你有用,祝你编码愉快:)
    • 实际上,我刚刚意识到这个解决方案不能按预期工作:(我会发布另一个答案来解释原因。
    【解决方案2】:

    实际上,Anil Maurya 提供的解决方案仅适用于使用 gem 提供的 link_to_add 通过 javascript 动态添加的项目。但对我来说,它会将new_association 留给已经存在的项目。

    为了正确识别每一个嵌套元素(甚至是深度嵌套的元素),可以使用f.index。优点是如果条目已经存在(意思是,如果它在数据库中),那么它将被它在数组中的索引替换。但是,使用link_to_add 会将f.index 替换为nested_form 自动生成的ID,就像Anil Maurya 的解决方案一样。

    对于深度嵌套的解决方案,如果您需要正确标记元素,您应该指定要渲染的部分,并且每次都使用不同的 f变量,您应该将其传递给部分

    例如:如果你有

    Main has_many :nested1s
    Nested1 has_many :nested2s
    Nested2 has_many :nested3s
    

    那么你的代码应该是这样的(我举了一个表格的例子,因为它更难):

    <%= nested_form_for @Main do |main_form| %>
    <table>
        <thead>
            <stuff />
        </thead>
        <%= main_form.fields_for :nested1s, :wrapper => false do |nested1_f| %>
            <%= render 'main/nested1_fields', nested1_f: nested1_f %>
        <% end %>
    

    _nested1_fields.html.erb

    <tbody class="fields">
        <tr>Stuff</tr>
        <tr>
            <table id="nested1-<%= nested1_f.index %>-nested2s">
            <thead>Stuff</thead>
            <%= nested1_f.fields_for :nested2s, :wrapper => false do |nested2_f| %>
                <%= render 'main/nested2_fields', nested1_f: nested1_f, nested2_f: nested2_f %>
            <% end %>
            </table>
        </tr>
        <tr><%= nested1_f.link_to_add 'add nested2', :nested2, :data => { :target => "#nested1-#{nested1_f.index}-nested2s"}, class: "btn btn-sm btn-success" %>
    </tbody>
    

    _nested2_fields.html.erb

    <tbody class="fields">
    ...
        <table id="nested1-<%= nested1_f.index %>-nested2-<%= nested2_f.index %>-nested3s">
           <%= fields_for :nested3s do |nested3_f| %>
           ...
    ...
    </tbody>
    

    另外需要注意的是 gemnested_form 只有在每个嵌套的字段集都由带有“字段”类的标签包装时才能正常工作

    【讨论】:

    • 谢谢。我花了很长时间才为自己的项目弄清楚这一点。实际上我在 Rails API 文档中找到了f.index。它应该只适用于 rails 4+,但对于使用 f.options[:child_index] 的旧版本,还有另一种方法可以做到这一点。请参阅此链接:stackoverflow.com/questions/4853373/rails-fields-for-with-index
    猜你喜欢
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 2011-04-09
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多