ruby - 使用 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>
解决方案
您正在应用分页逻辑两次。
首先,您从您的方法中仅选择一页结果:Assets.getAllAssets
count = Assets.getAssetsCount() 结果 = Assets.getAllAssets(offset, limit)
然后,您将 30 条记录will_paginate
的单页传递给 自己的分页方法,如果您只给它单页 30 条结果,则无法显示结果 31..60。
您应该放弃您的will_paginate
逻辑,或者更改您的getAllAssets
方法以返回类似 an 的ActiveRecord::Relation
内容,该内容可以通过will_paginate
.
推荐阅读
- javascript - 如何使用 AJAX 将 HTML 表单文件传递给 PHP
- javascript - 如何使用配置对数组进行排序
- java - UseCompressedOops UseCompressedClassPointers 在 jdk-13 和 jdk-15
- mongodb - Scala ReactiveMongo findAndUpdate 特定字段的占位符
- xml - CFXML - enablecfoutputonly 为“是”时“文件过早结束”
- c# - 从 Microsoft.Extensions.Configuration 将 JSON 作为字符串读取
- html - 使用 flex-basis 后无法垂直堆叠弹性项目
- python - 在python中使用socket libfrary从http中检索数据
- python - 使用 Python 更改图像中定义的颜色
- mongodb - 如何在 Mongo shell 中增加一行的限制