使用each_with_index和分页中断循环

时间:2014-11-29 22:02:22

标签: ruby-on-rails

在评论循环中,我尝试使用' each_with_index'在第一个3之后添加休息时间。像这样:

<% @comments.each_with_index  do |question, i| %>
<% if i == 2 %>
  This is a break
<% end %>
  <%= @comment.body %>
<% end %>

问题是我使用will_paginate gem为每页的评论3分页。这意味着,每隔3条评论就会重复休息一次,因为&#39; i&#39;每页重置一次。是否有关于这种或其他方式的工作来找到第三条评论?

2 个答案:

答案 0 :(得分:1)

它不是理想的解决方案,但你可以提供一个&#34;休息&#34;对于每个元素并使用css&#39; nth-child选择器只显示第三个。

.break {
    display: none;
}

div:nth-child(3) .break {
    display: block;
}

<div>1<span class="break">break</span></div>
<div>2<span class="break">break</span></div>
<div>3<span class="break">break</span></div> <!-- only this .break will be shown -->
<div>4<span class="break">break</span></div>
<div>5<span class="break">break</span></div>
<div>6<span class="break">break</span></div>

Fiddle

另一种选择是在外部范围内使用一个标志来防止&#34;中断&#34;从多次渲染。 (以下未经过测试。)

<%- render_break = true %>

<% @comments.each_with_index  do |question, i| %>
  <% if render_break && i == 2 %>
    This is a break
    <%- render_break = false %>
  <% end %>
  <%= @comment.body %>
<% end %>

答案 1 :(得分:0)

我找到了一个使用will_paginate的current_page方法的解决方案,以便中断只显示在第一页上。

<% @comments.each_with_index  do |question, i| %>    
<% if @comments.current_page == 1 && i == 2 %>
 Break
<% end %>
 <%= @comment.body %>    
<% end %>