首页 > 解决方案 > 使用 will_paginate 分页没有活动记录只显示第一页的值,下一页完全为空

问题描述

我正在尝试使用 Ruby on Rails 中的 will_paginate gem 对一些结果进行分页。问题是结果是非活动记录所以我按照这里的步骤:https://www.rubydoc.info/github/mislav/will_paginate/WillPaginate/Collection 能够做到这一点,但问题是现在我' m 只能看到第一页的结果,后面的页面完全是空的。我验证了查询有下一页的结果,一切看起来都很好。这是我写的代码,任何想法的家伙。谢谢!

我附上了一些图片来向大家展示它的外观,一张来自第一页的结果,另一张来自第二页的结果。

截图第一页结果 截图第二页结果

# controller AssetController
require Rails.root.to_s + '/config/initializers/will_paginate_array'

class AssetController < ApplicationController

  before_action :require_login

  def index
  @search = params[:search]
  @assetType = params[:assetType]
  @searchBy = params[:searchBy]

  limit = 30
  currentPage = params[:page];
  if currentPage == nil
    currentPage = 1
  end
  offset = (currentPage.to_i - 1) * limit

  count = Assets.getAssetsCount()
  results = Assets.getAllAssets(offset, limit)

  if results.class == Array
  @assets = results.paginate_custom_array(currentPage, limit, count)
  else
    # TODO
  end
end

# config/initializers/will_paginate_array.rb
require 'will_paginate/collection'

Array.class_eval do
  def paginate_custom_array(page = 1, per_page = 15, size)
    WillPaginate::Collection.create(page, per_page, size) do |pager|
      pager.replace self[pager.offset, pager.per_page].to_a
    end
  end
end

# views/asset/index.erb
<div id="assets_results">
  <%= render 'partials/assets_result' %>
</div>

# views/asset/index.js.erb
$("#assets_results").html("<%= escape_javascript render("partials/assets_result") %>");
$('#paginator').html('<%= escape_javascript(will_paginate(@assets, :remote => true).to_s) %>'); 

# views/partial/_assets_result.html.erb
<% @assets.each do |asset| %>
  <tr>
    <td>
     ...
    </td>
  </tr>
<% end %>
<div class="text-center">
  <div id="paginator"class="pagination pagination-lg">
    <%= will_paginate @assets, :remote => true %>
  </div>
</div>

标签: rubyruby-on-rails-4will-paginatepagination

解决方案


您正在应用分页逻辑两次

首先,您从您的方法中仅选择一页结果:Assets.getAllAssets

count = Assets.getAssetsCount() 结果 = Assets.getAllAssets(offset, limit)

然后,您将 30 条记录will_paginate的单页传递给 自己的分页方法,如果您只给它单页 30 条结果,则无法显示结果 31..60。

您应该放弃您的will_paginate逻辑,或者更改您的getAllAssets方法以返回类似 an 的ActiveRecord::Relation内容,该内容可以通过will_paginate.


推荐阅读