LoginSignup
4
6

More than 3 years have passed since last update.

【Ruby on Rails】kaminariとbootstrap4で日本語に対応したページネーションを実装する。

Last updated at Posted at 2020-03-20

はじめに

kaminariとbootstrap4でお洒落なページネーションを簡単に実装する方法をまとめました。

[前提]

bootstrap4がインストールされている

使い方

準備(インストール)

#Gemfile
gem 'kaminari'
gem 'bootstrap4-kaminari-views'
bundle install
#「bundle」だけでもOK

設定

日本語の設定(任意)

kaminariの日本語設定用ファイルを作成

config/locales/kaminari_ja.yml
ja:
  views:
    pagination:
      first: "« 最初"
      last: "最後 »"
      previous: "‹ 前"
      next: "次 ›"
      truncate: "..."

実装

Controller

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

@movies = Movie.where(status: "公開中").page(params[:page]).per(10)
#Movie.where(status: "公開中") ← Movieモデルからstatusが"公開中"のレコードを抽出
#page(params[:page]).per(10) ← ページパラメータを取得(10件毎)

※全件取得する場合は モデル名.all で指定

@movies = Movie.all.page(params[:page]).per(10)

View

Controllerで指定した変数を指定

#paginate @movies ← 変数 movies の中身を10件毎に表示
#theme: 'twitter-bootstrap-4 ← 使用したいテーマを指定
<%= paginate @movies, theme: 'twitter-bootstrap-4'%>

表示

スクリーンショット 2020-03-20 14.52.01.png

※上手く表示されない方は

  • サーバーの再起動
  • 設定ファイルの確認
  • perの設定(データ数以上のper値を設定するとページネーションが表示されません)

を確認してみてください!

参考
https://github.com/KamilDzierbicki/bootstrap4-kaminari-views

4
6
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
4
6