Help us understand the problem. What is going on with this article?

Kaminari使用時に undefined method 'per' for ActiveRecord::Relation と怒られた話

More than 1 year has passed since last update.

一体何番煎じなのかといった内容ですが備忘録も兼ねて、Kaminari を使用してページネーションを実装しようとした際にエラーが出て詰んだ話とその対処法です。

著者の環境

  • CentOS 6.9
  • Ruby 2.2.6
  • Rails 4.2.8

controller 側

articles_controller.rb
class ArticlesController < ApplicationController
  before_action :set_task, only: [:show, :edit, :update, :destroy]

  # GET /articles
  # GET /articles.json
  def index
    @articles = Article.order("created_at desc").page(params[:page]).per(3)
  end
(以下略)

 view 側

articles/index.html.rb
<%= paginate(@articles) %>

(以下略)

で、ページを見に行くと、

undefined method 'per' for ActiveRecord::Relation
と怒られる。。。

解決策

どうやら Kaminari とページネーション用のライブラリの WillPaginate が競合してしまっているらしい

ので config/initializers 配下に以下のファイルを作成してあげる。

kaminari.rb
Kaminari.configure do |config|
  config.page_method_name = :per_page_kaminari
end
will_pagenate.rb
if defined?(WillPaginate)
  module WillPaginate
    module ActiveRecord
      module RelationMethods
        def per(value = nil) per_page(value) end
        def total_count() count end
      end
    end
    module CollectionMethods
      alias_method :num_pages, :total_pages
    end
  end
end

ファイルを作成したらサーバー再起動をお忘れなく!

参考ページ

https://github.com/sferik/rails_admin/issues/1498
http://tech-brains.blogspot.jp/2012/11/kaminari-willpaginate-incompatibility.html

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした