LoginSignup
1
1

More than 3 years have passed since last update.

Rails Kaminariでページネーション機能を作る

Last updated at Posted at 2020-09-23

バージョン

・ruby 2.6.6
・rails 5.2.4.1

gem 'kaminari' を実装

 投稿機能を持ったアプリを作った際には、ページネーション機能はUX的にも必須です。
そこで、gemのKaminariを使って、ページネーション機能の実装を行います。

まずGemfileにkaminariを追加して、bundle installを実行

Gemfile
gem 'kaminari', '~> 1.2.0'
ターミナル
bundle install

Controllerを修正

 すでに投稿機能を作成し、投稿一覧ページがあるのであれば、Controlerを修正する必要があります。
 元々の自分の投稿一覧ページにおけるControllerは以下の通りです。

controllers/posts_controller.rb
def index
 @posts = Post.all
end

これらを次のように変更する。

controllers/posts_controller.rb
def index
 @posts = Post.page(params[:page]).per(10)
end

 Kaminariを追加したことで、各モデル上でpageとperというメソッドが使えるようになります。
pageメソッドの引数に現在のページ数を渡し、perの引数には何件でページを分割するかを渡します。
ここではperの引数に10を入れましたが、8件ずつページを区切りたいときは引数を8にします。

Viewの変更

 投稿一覧ページを表示する際には、each文を使うことが大体であると思いますが、rubyで用いる
<% end %> の後に <%= pagenate @posts %> と付け加えます。
 hamlを使った場合は、listの最後に = paginate @posts のように表記すると良いようです。
詳しくは、hamlを使って記事を書いている方がいらっしゃるので、そちらを参考にしてください。

views/posts/index.html.erb
 <% @posts.each do |post| %>
           .
           .
           .
 <% end %>
 <%= pagebate @posts %>

 ここまででミスがなければ、ページネーション用のリンクが自動で表示され、ページネーション機能が実装できます。
 しかし、見やすいデザインとまではなってないと思います。そこで、Bootstrapを利用して、デザインを整えます。すでにBootstrapを導入している方は、次のステップは飛ばしてください。

Bootstrapの導入

Bootstrapの導入には、yarnを利用してインストールするやり方、Bootstrapの公式サイトからダウンロードするやり方等ありますが、今回はCDNの方法で説明します。
ここの説明だけでは不安という方はhttps://www.youtube.com/watch?v=YY0mEyggH1E&t=713s
の動画で導入方法を説明しているものがありますので、そちらをご覧ください。

行うステップは2つ。
1つ目はheadタグの最後に、公式サイトにあるコードを記述。

layouts/application.html.erb
<head>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>

2つ目はbodyタグの最後に、公式サイトにあるコードを記述

layouts/application.html.erb
<body>

 <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
 <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
 <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

</body>

以上で導入が完了します。

Bootstrap4用のViewテンプレートを生成

 kaminariにはBootstrapやfoundationなどで使えるテーマが用意されています。
以下のコードをターミナルで実行すると「app/views/kaminari」配下にBootstrap4用のViewテンプレートが生成されます。このViewはkaminariデフォルトのViewより優先して適用されます。

ターミナル
rails g kaminari:views bootstrap4

ここまで完了すると見た目も良いデザインとなります。
うまくいかない時はサーバーを再起動してみてください。

また、英語の表記のままでは嫌だという人は日本語表記にする操作を行います。
「config/locales/kaminari_ja.yml」を追加し、以下のように記述します。

config/locales/kaminari_ja.yml
ja:
  views:
      pagination:
        first: '最初'
        last: '最後'
        previous: '前'
        next: '次'
        truncate: '...'

ここまでで日本語が適用されていないときは「config/application.rb」の中に config.i18n.default_locale = :ja を追加する。
全体的に見ると、以下のようになります。

config/application.rb
require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Theclo
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
    config.i18n.default_locale = :ja
    config.time_zone = 'Tokyo'
  end
end

以上で実装完了です。
うまくいかない時は再度サーバーの再起動をしてみてください。
皆さんの参考になれば幸いです。

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