如何使用 kaminari 助手对自定义资源进行分页?
How to paginate custom resources with kaminari helpers?
我在休息时查询了一些自定义资源 API。我想使用 kaminari 的分页视图助手(例如页面链接)。
我了解 kaminari 可以 paginate array-like resources 当它们全部可用时,但是,我的资源一次查询和存储非常昂贵。
发现这篇文章有用但已过时:https://kirshatrov.com/2015/11/08/kaminari-custom-query/
最终编写了我自己的适配器:
class KaminariAdapter
def initialize(page)
@page = page.to_i
@limit = 1
end
def entries(page)
raise "Must be implemented by subclass"
end
def total_count
raise "Must be implemented by subclass"
end
def entry_name(*arg)
@entry_name ||= 'entry'.freeze
end
def current_page
@page
end
def total_pages
@total_pages ||= (total_count.to_f / @limit).ceil
end
def limit_value
@limit
end
def offset
(@page - 1) * @limit
end
def offset_value
offset
end
def all
entries(@page)
end
def size
all.count
end
end
Children 必须实现 entries(page)
和 total_count
方法。这是一个例子:
class CustomPagination < KaminariAdapter
def initialize(*args)
super
@all_entries = [1, 2, 3, 4, 5, 6, 7]
@limit = 2
end
def entries(page)
@all_entries[offset..(offset + @limit - 1)]
end
def total_count
@all_entries.count
end
end
可以这样使用:
test_controller.rb
def index
@entries = CustomPagination.new(params[:page].to_i)
end
test/index.html.erb
<% @entries.all.each do |entry| %>
<%= entry %>
<% end %>
<%= paginate @entries %>
<%= page_entries_info @entries %>
我在休息时查询了一些自定义资源 API。我想使用 kaminari 的分页视图助手(例如页面链接)。
我了解 kaminari 可以 paginate array-like resources 当它们全部可用时,但是,我的资源一次查询和存储非常昂贵。
发现这篇文章有用但已过时:https://kirshatrov.com/2015/11/08/kaminari-custom-query/
最终编写了我自己的适配器:
class KaminariAdapter
def initialize(page)
@page = page.to_i
@limit = 1
end
def entries(page)
raise "Must be implemented by subclass"
end
def total_count
raise "Must be implemented by subclass"
end
def entry_name(*arg)
@entry_name ||= 'entry'.freeze
end
def current_page
@page
end
def total_pages
@total_pages ||= (total_count.to_f / @limit).ceil
end
def limit_value
@limit
end
def offset
(@page - 1) * @limit
end
def offset_value
offset
end
def all
entries(@page)
end
def size
all.count
end
end
Children 必须实现 entries(page)
和 total_count
方法。这是一个例子:
class CustomPagination < KaminariAdapter
def initialize(*args)
super
@all_entries = [1, 2, 3, 4, 5, 6, 7]
@limit = 2
end
def entries(page)
@all_entries[offset..(offset + @limit - 1)]
end
def total_count
@all_entries.count
end
end
可以这样使用:
test_controller.rb
def index
@entries = CustomPagination.new(params[:page].to_i)
end
test/index.html.erb
<% @entries.all.each do |entry| %>
<%= entry %>
<% end %>
<%= paginate @entries %>
<%= page_entries_info @entries %>