LoginSignup
10
12

More than 5 years have passed since last update.

kaminariのページネーション機能でundefined method `page' for #<Array:~>とエラーになった時の対処法

Posted at

kaminariを使ったページネーション機能は、かなり簡単に実装できるのが良いですよね。
そんなkaminariですが、Arrayオブジェクトに対しては通常の実装だと、

undefined method `page' for #<Array:~>

とエラーが出てしまいますので、対処法をまとめます。

kaminari実装前

商品(Product)オブジェクトをお気に入り数順で、ランキングするメソッドです。

class RankingsController < ApplicationController
  def like
    @ranking_counts = Like.ranking
    @products = Product.find(@ranking_counts.keys)
  end
end

エラー対処前

通常のKaminariの利用だと、このように実装します。が、これだとエラーになります。

class RankingsController < ApplicationController
  def like
    @ranking_counts = Like.ranking
    @products = Product.find(@ranking_counts.keys).page(params[:page]).per(10)
  end
end

エラー対処後

@productsを引数に、Kaminari.paginate_arrayを追記することで、実装ができました。

class RankingsController < ApplicationController
  def like
    @ranking_counts = Like.ranking
    @products = Product.find(@ranking_counts.keys)
    @products = Kaminari.paginate_array(@products).page(params[:page]).per(10)
  end
end

findwhereメソッドを利用するとArrayオブジェクトが生成されるので、上記のような対処が必要です。

参考

kaminariでundefined method `page' for # Array:0x000xxxxxxと出た

10
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
12