我有一个部分:views/nodes/_node.html.erb
,我会在任何视图上呈现:
<%= render @nodes %>
当我像这样呈现它时,根据Rails指南,我可以使用部分中的node_counter
作为计数器来跟踪部分内的各种元素(或者说分配每次部分增加的ID)被渲染)。
现在我想使用相同的部分,但不是那样渲染,而是像这样:
<%= render partial: "nodes/node", locals: {node: event.eventable} %>
当我这样做时,我收到了这个错误:
undefined local variable or method `node_counter' for #<#<Class:0x007fa3b6ca9778>:0x007fa3b58a60c8>
那是因为我从未指定/传递node_counter
作为局部变量。
那么我如何指定node_counter
从0开始并且每次渲染部分时总是递增 - 如果我不能用Rails方式做的话?
作为参考,Rails指南说明了这一点:
Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by _counter. For example, if you're rendering @products, within the partial you can refer to product_counter to tell you how many times the partial has been rendered. This does not work in conjunction with the as: :value option.
答案 0 :(得分:1)
在您的通话视图中,您可以使用each_with_index
:
<% @foo.each_with_index do |foo, index| %>
<%= render 'nodes/node', f:foo, node_counter:index %>
然后在_nodes/node
部分中,node_counter
将从0开始递增。
第二次通话中node_counter
无法使用的原因是您使用成员而非集合来调用部分内容。