Rails 3: undefined method `page' for #

2020-06-07 04:13发布

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?

5条回答
2楼-- · 2020-06-07 04:39

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]
查看更多
Fickle 薄情
3楼-- · 2020-06-07 04:46

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

查看更多
ゆ 、 Hurt°
4楼-- · 2020-06-07 04:47

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)
查看更多
祖国的老花朵
5楼-- · 2020-06-07 04:57

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])
查看更多
一夜七次
6楼-- · 2020-06-07 04:57

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

查看更多
登录 后发表回答