13
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-06-07

一体何番煎じなのかといった内容ですが備忘録も兼ねて、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

13
8
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
13
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?