LoginSignup
8
9

More than 5 years have passed since last update.

Rails ページネーションのperとpageを一つのscopeで実現する

Posted at

やりたいこと

ページングを実施する際に、pageやperを渡すのですが、下記のようにparamsとそれに対応したキーを渡す必要があり、少しコードが長くなり気味。

Item.page(params[:page]).per(params[:per])

そこで、一つのチェインでpaginateを実現する方法を紹介します。

Concernsを使って、paginateのscopeを追加

models/concerns/paginate.rb
module Paginate
  extend ActiveSupport::Concern
  include Kaminari::PageScopeMethods

  included do
    scope :paginate, ->(p) { page(p[:page]).per(p[:per]) }
  end
end

使うときは、Modelにmoduleをincludeします。

class Item < ActiveRecord::Base
  include Paginate
end

すると、下記のように一つのscopeでpaginateを実現できます。

Item.paginate(params)
8
9
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
8
9