2

似乎 will_paginate 和 Kaminari 都与 ActiveRecord 密切相关?如果数据是通过API获取的,比如

http://www.foo.com/fetch_data?type=products&offset=100&count=20

那么如何使用 will_paginate 或 Kaminari 进行分页呢?如果不能,是否有其他分页解决方案可以在这种情况下工作?

4

2 回答 2

3

我已经为我的acts_as_indexed 插件在非AR 集上进行了分页。

在您的情况下,它的工作方式如下:

def fetch(page=1, per_page=10)
  total_entries = 1000 # Or whatever method you choose to find the total entries.

  returning ::WillPaginate::Collection.new(page, per_page, total_entries) do |pager|
    url = "http://www.foo.com/fetch_data?type=products&offset=#{pager.offset}&count=#{pager.per_page}"

    results = fetch_example(url)# fetch the actual data here.

    pager.replace results
  end
end

控制器:

def index
  @records = fetch(params[:page])
end

意见:

<%= will_paginate @records %>

填写您自己的获取和处理数据的方法,并计算出总条目。

于 2011-04-01T08:48:17.563 回答
0

我编写了自己的函数来对对象数组进行分页。您可以修改代码以满足自己的需要:

def array_paginate page, per_page, array
  page = page.to_i
  per_page = per_page.to_i
  total_entries = array.count

  total_pages = (total_entries / per_page.to_f).ceil
  data = format_records( array[ (page-1)*per_page..page*per_page-1] )

  {
    page: page,
    total_pages: total_pages,
    data: data,
  }
end
于 2015-04-22T07:44:45.260 回答