【问题标题】:Pass index variable to the fields_for tag and inside the render partial将索引变量传递给 fields_for 标记并在渲染部分内部
【发布时间】:2013-03-24 01:04:54
【问题描述】:

我将 cocoon 用于动态/嵌套字段/表单。

但是,我无法在部分文件中传递索引变量。

这是我的 _form.html.erb 中的内容:

 <% @project_procurement_management_plan.items.each_with_index do |item, index | %>
  <%= f.fields_for :items, item, :child_index => index do |builder| %>
    <%= render 'item_fields', :f => builder, :g=>index %>
  <% end %>
<% end %>
<div>
  <%=link_to_add_association 'Add Item', f, :items, class:"btn btn-success totheleft" %>
</div>

在我的 _item_fields.html.erb 中:

<%= f.select :category_id, Category.all.map{ |c| [c.code, c.id] }, {:prompt=>""},{class:"cat-code #{g}",required:true} %>

上面写着:

#

的未定义局部变量或方法“g”

很明显,变量g 作为索引无法在我的部分中读取。

是否有任何解决方法可以将索引变量正确传递给 fields_for 并进入我的渲染中。

谢谢。

【问题讨论】:

    标签: ruby-on-rails cocoon-gem


    【解决方案1】:

    您不必自己迭代这些项目! fields_for 会为你做这件事。

    删除循环&lt;% @project_procurement_management_plan.items.each_with_index do |item, index | %&gt;

    你现在还需要索引吗?

    【讨论】:

    • 实际上我需要 fields_for 来进行索引计数。这样我就可以使用我的 javascript 代码调用索引。这就是为什么我有这个class: "cat-code #{g} "
    【解决方案2】:

    请考虑使用“本地人”

    <%= render :partial => 'item_fields', :locals => { :g => index, :f => builder } %>
    

    【讨论】:

    • 如果他使用:locals,那么他也必须使用:partial,对吗? render partial: 'item_fields', locals: {}。但我不认为这是他问题的根源。
    • 实际上,partial 仍然没有得到 :g 变量。但也谢谢。
    【解决方案3】:

    我通过在我的@parameter 中设置这样的@parameter 解决了这样的问题(在haml 中):

    questions.html.haml

    - @answer_index = 0
    .answers
      = f.fields_for :answers
      = f.link_to_add "Add an answer", :answers
    

    answers.html.haml

    .answer
      .field
        = f.label :answer, "Answer #{('A'..'Z').to_a[@answer_index]}"
        = f.radio_button :correct , 1, {onclick: "check_answer(this);"}
        = f.text_field :answer
        %span.remove
          = f.link_to_remove "remove"
    
    - @answer_index += 1
    

    不确定是否可以传递 @answer_index 之类的 @ 变量

    所以对你来说,它可能看起来像(但不完全是,我敢肯定):

    _form.html.erb

      <%= @item_index = 0 %>
      <%= f.fields_for :items do |builder| %>
        <%= render 'item_fields', :f => builder %>
        <%= @item_index += 1 %>
      <% end %>
    <% end %>
    <div>
      <%=link_to_add_association 'Add Item', f, :items, class:"btn btn-success totheleft" %>
    </div>
    

    _item_fields.html.erb

    <%= f.select :category_id, Category.all.map{ |c| [c.code, c.id] }, {:prompt=>""},{class:"cat-code #{@item_index}",required:true} %>
    

    【讨论】:

      猜你喜欢
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多