2011-11-23 59 views
0

我在我的Rails 3应用程序中遇到问题。我将Ajax应用于表单,但无法在视图中呈现新创建的对象。目前问题似乎是Rails 3计数器。当我提交表单无需重新加载页面,我的控制台呈现如下:哪里定义_counter在Rails 3集合

ActionView::Template::Error (undefined local variable or method `superlative_counter' for #<#<Class:0x105bdd4a8>:0x105bd6a40>): 
1: <% if superlative_counter + 1 == superlative_count && superlative_count > 1 %> 
2: <li class="superlative"> 
3:  and <span title="<%=h superlative.name %>"><%=h superlative.body %><p class="deleteSup"><%= link_to 'x', superlative_path(superlative), :method => :delete, :remote => true, :confirm => "Are you sure you want to remove this superlative?" %></p></span> 
4: </li> 

作为一个初学者,我不知道在哪里我的代码定义superlative_counter。我以为这个计数器只包含在Rails中:

Rails还在由集合调用的部分中创建一个计数器变量,以该集合的成员后跟_counter命名。例如,如果您渲染@products,则可以在部分内引用product_counter来告诉您已渲染部分的次数。这不适用于:as =>:value选项。

下面是如何使我的收藏:

<li><%= "#{@profile.first_name}" %>&nbsp;is most likely to:&nbsp;</li><%= render :partial => 'superlatives/superlative', :collection => @profile.superlatives, :locals => {:superlative_count => @profile.superlatives.length} %> 

这里是我的_superlative.html.erb部分:

<% if superlative_counter + 1 == superlative_count && superlative_count > 1 %> 
    <li class="superlative"> 
    and <span title="<%=h superlative.name %>"><%=h superlative.body %><p class="deleteSup"><%= link_to 'x', superlative_path(superlative), :method => :delete, :remote => true, :confirm => "Are you sure you want to remove this superlative?" %></p></span> 
    </li> 
<% elsif superlative_count == 1 %> 
    <li class="superlative"> 
    <span title="<%=h superlative.name %>"><%=h superlative.body %><p class="deleteSup"><%= link_to 'x', superlative_path(superlative), :method => :delete, :remote => true, :confirm => "Are you sure you want to remove this superlative?" %></p></span> 
    </li> 
<% else %> 
<li class="superlative"> 
    <span title="<%=h superlative.name %>"><%=h superlative.body %><p class="deleteSup"><%= link_to 'x', superlative_path(superlative), :method => :delete, :remote => true, :confirm => "Are you sure you want to remove this superlative?" %></p></span>,&nbsp; 
</li> 
<% end %> 

如果有人可以帮我找出我应该在哪里定义计数器我会感激!

回答

0

您无需在任何地方定义计数器。它由Rails本身初始化。
对我来说,你的代码看起来很好。
不过,试试这个:
保存@profile.superlatives在变量@superlatives然后执行:

...:收集=> @superlatives,:当地人=> {:superlative_count => @ superlatives.length} %>

+0

谢谢!我应该在哪里做? – tvalent2