Paginating an Array in Ruby With Will_Paginate

Ruby on Rails will_paginate an array

will_paginate 3.0 is designed to take advantage of the new ActiveRecord::Relation in Rails 3, so it defines paginate only on relations by default. It can still work with an array, but you have to tell rails to require that part.

In a file in your config/initializers (I used will_paginate_array_fix.rb), add this

require 'will_paginate/array'

Then you can use on arrays

my_array.paginate(:page => x, :per_page => y)

Paginating an Array in Ruby with will_paginate

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.

Use will_paginate gem with an array

Just put require 'will_paginate/array' at the top of any controllers that will use array pagination.

will_paginate on array only displays first page of items

I think you missing page: params[:page] in index controller, this is how will_paginate know what page you currently now

def index
@items = Array.new
API.items.all! do |i|
@items << i
end
@paginated_items = @items.paginate(page:params[:page],per_page:25)
end

will_paginate JSON array

Figured it out.

added require 'will_paginate/array' to my will_paginate_helper.rb and then paginated the collection AFTER .to_json, e.g. in my helper (or your controller):

games = Game.order(game_date: :desc).postgame.to_json
@games = Oj.load games
@games = @games.paginate(page: params[:page], per_page: 10)

Works with will_paginate or js_will_paginate just as before.

Rails WillPaginate::Collection not paginating Array

Went and re-read the collection.rb and array.rb libraries.

With controller stating:

require "will_paginate/array"

@vgps = vgp.sort_by{|e| e.rate}
@vgps = @vgps.paginate(:page => params[:page], :per_page => 30)

This is all that is necessary for a sorted array.

Rails hash to will_paginate format

will_paginate can make use of plain arrays instead of ActiveRecord scopes.

You just need to treat your data before. There is plenty of resource on how to do it:

https://makandracards.com/makandra/13521-will_paginate-can-paginate-plain-ruby-arrays

https://gist.github.com/denmarkin/817327



Related Topics



Leave a reply



Submit