1
1

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.

【Rails】kaminariを使用して基本的なページネーション機能を実装する

Posted at

前提

bundlerを使用して、Gemfileでgemを管理していることを想定しています。

使い方

準備(インストール)

1.Gemfile内にgem kaminariを記述

# Gemfile 
gem 'kaminari'

2.kaminariをインストール

$ bundle install
# 「bundle」だけでもOK

設定

設定ファイル作成

1.設定ファイルを作成する

$ rails g kaminari:config

2.設定ファイルが作成される

config/initializersディレクトリ配下に「kaminari_config.rb」ファイルが作成されます。
作成されたファイルをいじることで、「kaminari」のデフォルト設定を変えることができます。

以下の記事に詳しく書かれていたので参考にしてみて下さい。
Railsライブラリ紹介: ページングを行う「kaminari」

kaminari_config.rb
# frozen_string_literal: true
Kaminari.configure do |config|
  # config.default_per_page = 25
  # config.max_per_page = nil
  # config.window = 4
  # config.outer_window = 0
  # config.left = 0
  # config.right = 0
  # config.page_method_name = :page
  # config.param_name = :page
  # config.params_on_first_page = false
end

Controller

Controllerでページパラメータ(params[:page])を取得します。

@users = User.order(:id).page params[:page]
# User.order(:id) ← Userモデル(usersテーブル)をid順にら並べている
# .page params[:page] ← 大切なのはここ。ページパラメータを取得している。

Views

views部分で以下のようにControllerで定義した変数名を使いましょう。

#  @usersはControllerで定義した変数名
<%= paginate @users %>

以上で基本的なページネーションの機能が付けれるかと思います。

※上手く表示されていない時は、設定ファイルを保存しているかやサーバーの再起動をしているかなどをチェックしてみてください!

より詳しい使い方は以下を参考にしてみてください!
(表示するテキストを変えたり、テーマを変えたりとかもできます。)
【参考】https://github.com/kaminari/kaminari

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?