Paginating an Array in Ruby with will_paginate

我是研究僧i 提交于 2019-11-26 07:33:27

问题


I have an array @level1 which looks like this :

[[3.0, 4, 2], [2.0, 48, 3], [2.1, 56, 4], ............]

I want to apply pagination on this array such each page displays only a few rows at once. I tried this:

@temp1 = @level1.paginate(:page => params[:page])

But it throws the following error:

undefined method `paginate\' for [[3.0, 4, 2], [2.0, 48, 3], [2.1, 56, 4]]:Array

How can I perform pagination on this using will_paginate?


回答1:


Sure, you can use WillPaginate::Collection to construct arbitrary pagination across collections. Assuming an array called values:

@values = WillPaginate::Collection.create(current_page, per_page, values.length) do |pager|
  pager.replace values
end

You can then treat @values just like any other WillPaginate collection, including passing it to the will_paginate view helper.




回答2:


See https://github.com/mislav/will_paginate/blob/master/lib/will_paginate/array.rb

Just require 'will_paginate/array' before you try it and it will work just fine. If it were me, I'd put that in say config/initalizers/will_paginate_extensions.rb so it's available right away and from everywhere.




回答3:


Given a collection array in a Rails project

will_paginate ~>3.0.5

collection.paginate(page: params[:page], per_page: 10)

returns the pagination for the array values.

Do not forget require 'will_paginate/array' on top of the controller.




回答4:


This is my example based in the answer of @chris-heald

products = %w(i love ruby on rails)
@products = WillPaginate::Collection.create(params[:page], params[:per_page], products.length) do |pager|
   pager.replace products[pager.offset, pager.per_page]
end



回答5:


I wasn't really happy with the answers provided in this thread.

I came up with this solution.

# app/lib/paged_array.rb

require 'will_paginate/array'

class PagedArray
  delegate_missing_to :@paged_collection

  def initialize(collection, page: 1, per_page: 20)
    @paged_collection = collection.paginate(
      page: page,
      per_page: per_page
    )
  end
end

And you can use it like that:

superheroes = %w[spiderman batman superman ironman]

PagedArray.new(superheroes, page: 1, per_page: 2)

I like this solution since it's explicit and you are not polluting your standard classes.

That being said, you are dependent of rails since I use "delegate_missing_to".



来源:https://stackoverflow.com/questions/13187076/paginating-an-array-in-ruby-with-will-paginate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!