ページネーション機能を追加 gem 'kaminari'

今回は、gem 'kaminari'を使用してページネーション機能を追加していきたいと思います。

下の図は、僕が今日作ったアプリの結果一覧表示なのですが、悲惨ですよね。

横断幕みたいになっちゃってます。。

[![Image from Gyazo](https://i.gyazo.com/752d26b73f28bb9e3d58eb0ec5cf66c2.png)](https://gyazo.com/752d26b73f28bb9e3d58eb0ec5cf66c2)

gemを使用して1ページにつき6記事までしか表示されないようにしていきます。

 

ざっくりフローチャート

・gemを入れてbundle

・controllerを編集

・viewを編集

・configを編集

それではやっていきます。

github.com

 

インストール方法

Gemfileに下記コマンドを追加。

gem 'kaminari'

そしてターミナルでbundleをします。

% bundle

kaminariをインストールすることができたら、一覧表示させたいアクションを下記の通り編集させましょう。Optime.all以下のincludes(:user)は、N+1問題を回避するためにあらかじめUserとアソシエーションをつけているだけなので、Optime.allだけでも構いません。

編集前

class OptimesController < ApplicationController
def index
@optimes = Optime.all.includes(:user).order(created_at: :desc)
@user = User.last
end

編集後(allをpage(params[:page])に変更している。)

class OptimesController < ApplicationController
def index
@optimes = Optime.page(params[:page]).per(6).includes(:user).order(created_at: :desc)
@user = User.last
end

 

そしてRails.root/config/locales ディレクトリを下記のように編集しましょう。

en:
  views:
    pagination:
      first: "&laquo; First"
      last: "Last &raquo;"
      previous: "&lsaquo; Prev"
      next: "Next &rsaquo;"
      truncate: "&hellip;"
  helpers:
    page_entries_info:
      one_page:
        display_entries:
          zero: "No %{entry_name} found"
          one: "Displaying <b>1</b> %{entry_name}"
          other: "Displaying <b>all %{count}</b> %{entry_name}"
      more_pages:
        display_entries: "Displaying %{entry_name} <b>%{first}&nbsp;-&nbsp;%{last}</b> of <b>%{total}</b> in total"
 

すると、劇的BeforeAfterが始まります

Before

[![Image from Gyazo](https://i.gyazo.com/39f3d0a6509a609a5c4e6d9da1a10c56.png)](https://gyazo.com/39f3d0a6509a609a5c4e6d9da1a10c56)

After

[![Image from Gyazo](https://i.gyazo.com/3ab8585d0253f922f76049962c982ec4.png)](https://gyazo.com/3ab8585d0253f922f76049962c982ec4)

まだページネーションの名前が英語になってしまっているので編集しましょう。

config/application.rbに下記コードを追記

config.i18n.default_locale = :ja
config.i18n.load_path += Dir[Rails.root.join('config/locales/**/*.{rb,yml}').to_s]

そしてGemfileに下記gemを追加しましょう。

#国際化
gem 'rails-i18n'

その後、例によって$ bundleをします。

そして、config/initializer/locales/ja.ymlを下記のように編集します。

ja:
views:
pagination:
first: "&laquo; 最初"
last: "最後 &raquo;"
previous: "&lsaquo; 前"
next: "次 &rsaquo;"
truncate: "&hellip;"
helpers:
page_entries_info:
one_page:
display_entries:
zero: "%{entry_name} はありません"
one: "<b>1</b> 件の%{entry_name}を表示"
other: "%{count}</b> %{entry_name}を表示"
more_pages:
display_entries: "<b>%{total}</b>件中の%{entry_name} を表示<b>%{first}&nbsp;-&nbsp;%{last}</b> "

 すると、画像のように、ページネーション部分が日本語表記になったかと思います。

[![Image from Gyazo](https://i.gyazo.com/9f2e8348a96339b4eb229d60f8d129ca.png)](https://gyazo.com/9f2e8348a96339b4eb229d60f8d129ca)

これで一覧画面が綺麗になりました〜。よかった。