0

我正在将茧用于动态/嵌套字段/表单。

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

这是我的 _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} %>

它说:

#<#:0x007f82dadeacd8> 的未定义局部变量或方法“g”

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

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

谢谢你。

4

3 回答 3

0

I solved something like this (in haml) by setting a @parameter in mine like so:

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

Not sure if you can pass an @ variable like @answer_index

So for you it might look something like (but not exactly, I'm sure):

_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} %>
于 2014-03-27T22:13:00.720 回答
0

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

删除循环<% @project_procurement_management_plan.items.each_with_index do |item, index | %>

你现在还需要索引吗?

于 2013-03-24T01:12:16.083 回答
0

请考虑使用“本地人”

<%= render :partial => 'item_fields', :locals => { :g => index, :f => builder } %>
于 2013-03-24T01:13:11.260 回答