首页 > 解决方案 > 使用 will_paginate 在 erb Rails 中显示最后一条记录

问题描述

我正在尝试使用此布局显示我的模型论坛上的最后一个实例记录:

一些随机论坛
一些随机论坛

最后的

最后记录的论坛

我正在使用 gem will_paginate,它允许我每页显示 10 个论坛。问题是布局正在工作但适用于每个页面。每 10 个论坛,一个被确定为“最后一个”。显然,我希望只有一个论坛被确定为最后一个。

这是我的代码:

<div class="wrapping">


<% @tribunes.each do |tribune| %>
  <div class="container">
    <div class="mouse-out-container"></div>
    <div class="row">
      <% if tribune == @tribunes.last
%>
  <h1>Last</h1>
  <div class="col-xs-12 col-md-12">
    <div class="card">
      <div class="card-category">Popular</div>
      <div class="card-description">
        <h2><%= tribune.title %></h2>
        <p><%= tribune.content.split[0...25].join(' ') %>...</p>
      </div>
      <img class="card-user" src="https://kitt.lewagon.com/placeholder/users/tgenaitay">
      <%= link_to "", tribune, :class => "card-link" %>
    </div>
  <% else %>


  <div class="col-xs-12 col-md-12">
    <div class="card">
      <div class="card-category">Popular</div>
      <div class="card-description">
        <h2><%= tribune.title %></h2>
        <p><%= tribune.content.split[0...25].join(' ') %>...</p>
      </div>
      <img class="card-user" src="https://kitt.lewagon.com/placeholder/users/tgenaitay">
      <%= link_to "", tribune, :class => "card-link" %>
    </div>

      </div>
      <% end %>
      <% end %>
    </div>

    <div class="center-paginate">
      <%= will_paginate @tribunes, renderer: BootstrapPagination::Rails %>
    </div>

  </div>
</div>

标签: ruby-on-railsrubyerbwill-paginate

解决方案


当所有的Goole-fu都失败时,我们必须深入挖掘源代码。在那里我们发现了一些有趣的方法:

# Any will_paginate-compatible collection should have these methods:
#   current_page, per_page, offset, total_entries, total_pages
#
# It can also define some of these optional methods:
#   out_of_bounds?, previous_page, next_page

从这些来看,该方法看起来很有趣,因为如果没有更多页面next_page,它似乎会返回。nil

现在我们可以构造循环:

<% @tribunes.each do |tribune| %>
  <% if !@tribunes.next_page && tribune == @tribunes.last %>
     <!-- We're on the last page and the last tribune of that page -->
     Last tribune content
  <% else %>
     <!-- We still have tribunes to go -->
     Normal tribune content
  <% end %>
<% end %>

推荐阅读