Tyler
Tyler

Reputation: 11509

will_paginate not working with arrays

I've added

# config/initializers/will_paginate_array_fix.rb
require 'will_paginate/array'

but still do not seem to be getting pagination support for arrays, eg:

def index
  @array = (1..100).to_a.paginate(params[:page])
end
# gives TypeError: can't convert Symbol into Integer

It works fine with models, and I get

defined? WillPaginate # => constant
ActiveRecord::Base.respond_to? :paginate # => true
# but:
Array.respond_to? :paginate # => false

Anyone know what I am missing to get pagination support for arrays?

Upvotes: 1

Views: 2856

Answers (1)

Tyler
Tyler

Reputation: 11509

Found the answer by looking at source code in will_paginate/array:

def paginate(options = {})
  page     = options[:page] || 1
  per_page = options[:per_page] || WillPaginate.per_page
  total    = options[:total_entries] || self.length

  WillPaginate::Collection.create(page, per_page, total) do |pager|
    pager.replace self[pager.offset, pager.per_page].to_a
  end
end

So for arrays, you have to use .paginate (not .page), and you have to pass it as a hash. So the following works:

def index
  @array = (1..100).to_a.paginate(page: params[:page])
end

Upvotes: 5

Related Questions