Chris Bolton
Chris Bolton

Reputation: 2926

Rails 3: undefined method `page' for #<Array:0xafd0660>

I can't get past this. I know I've read there isn't a page method for arrays but what do I do?

If I run Class.all in the console, it returns #, but if I run Class.all.page(1), I get the above error.

Any ideas?

Upvotes: 29

Views: 17306

Answers (5)

aloucas
aloucas

Reputation: 3037

When you get an undefined method page for Array, probably you are using kaminari gem and you are trying to paginate your Model inside a controller action.

NoMethodError at /
undefined method `page' for # Array

There you need to remind yourself of two things, that the collection you are willing to paginate could be an Array or an ActiveRecordRelation or of course something else.

To see the difference, lets say our model is Product and we are inside our index action on products_controller.rb. We can construct our @products with lets say one of the following:

@products = Product.all

or

@products = Product.where(title: 'title')

or something else... etc

Either ways we get your @products, however the class is different.

@products = Product.all
@products.class
=> Array

and

@products = Product.where(title: 'title')
@products.class
=> Product::ActiveRecordRelation

Therefore depending on the class of the collection we are willing to paginate Kaminari offers:

@products = Product.where(title: 'title').page(page).per(per)
@products = Kaminari.paginate_array(Product.all).page(page).per(per)

To summarise it a bit, a good way to add pagination to your model:

def index
  page = params[:page] || 1
  per  = params[:per]  || Product::PAGINATION_OPTIONS.first
  @products = Product.paginate_array(Product.all).page(page).per(per)

  respond_to do |format|
    format.html
  end

end

and inside the model you want to paginate(product.rb):

paginates_per 5
# Constants
PAGINATION_OPTIONS = [5, 10, 15, 20]

Upvotes: 5

joelvh
joelvh

Reputation: 17138

I fixed the issue by invoking Kaminari's hooks manually. Add this line to run in one of your first initializers:

Kaminari::Hooks.init

I posted more details in another answer:

undefined method page for #<Array:0xc347540> kaminari "page" error. rails_admin

Upvotes: 1

DaveStephens
DaveStephens

Reputation: 1126

Kaminari now has a method for paginating arrays, so you can do something like this in your controller:

myarray = Class.all
@results = Kaminari.paginate_array(myarray).page(params[:page])

Upvotes: 12

Bashar Abdullah
Bashar Abdullah

Reputation: 1545

I had the same error. Did bundle update then restarted the server. One of the two fixed it.

Upvotes: 0

James Chen
James Chen

Reputation: 10874

No Array doesn't have a page method.

Looks like you are using kaminari. Class.all returns an array, thus you cannot call page on it. Instead, use Class.page(1) directly.

For normal arrays, kaminari has a great helper method:

Kaminari.paginate_array([1, 2, 3]).page(2).per(1)

Upvotes: 44

Related Questions