Rails 3: undefined method `page' for #<Array:0xafd0660>
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)
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])
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]