kaminariというgemを使ってページネーションを実装していきます。ある程度データが必要なのでダミーデータはFakerを使って投入します。kaminariにはあらかじめテーマがいくつかあるようですが、今回はbootstrapを適用したいと思います。i18nで日本語化もします。
Kaminari
https://github.com/kaminari/kaminari
Faker
https://github.com/stympy/faker
https://remonote.jp/rails-gem-faker
バージョンはこちらです
1 2 3 4 5 |
ruby 2.4.0 rails 5.1.6 kaminari 1.1.1 kaminari-bootstrap 3.0.1 faker 1.9.1 |
準備
scaffoldでユーザーを作って進めていきます。
1 2 |
$ rails g scaffold User name:string $ rails db:migrate |
Gemfile
1 2 3 4 |
gem 'kaminari' gem 'kaminari-bootstrap' gem 'bootstrap-sass' gem 'faker' |
1 |
$ bundle install |
application.cssの方はScssを使うのでリネームします。
application.css => application.scss (application.css.scssとしてもOK!)
1 2 |
@import "bootstrap-sprockets"; @import "bootstrap"; |
fakerでseedデータを入れる
db/seeds.rb
1 2 3 4 5 |
50.times do User.create( name: Faker::Name.name_with_middle ) end |
1 |
$ rails db:seed |
kaminariを適用する
次のコマンドでkaminariの設定ファイルが生成されます。
1 |
$ rails g kaminari:config |
config/initializers/kaminari_config.rb
1 2 3 4 5 6 7 8 9 10 11 |
Kaminari.configure do |config| config.default_per_page = 5 #1ページ辺りの項目数 # 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 |
config.default_per_page = 5で全体として1ページ辺りの項目数を設定するか、モデル毎に設定する場合は次のように書きます。
app/models/user.rb
1 2 3 |
class User < ApplicationRecord paginates_per 5 end |
app/controllers/users_controller.rb
1 2 3 |
def index @users = User.page(params[:page]) end |
一覧表示するデータの上と下の2箇所に、kaminariのヘルパーを一行づつ追記します。
app/views/users/index.html.erb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<h1>Users</h1> <%= page_entries_info @users %> <!-- 追加箇所 --> <table class="table"> <thead> <tr> <th>Name</th> <th colspan="3"></th> </tr> </thead> <tbody> <% @users.each do |user| %> <tr> <td><%= user.name %></td> <td><%= link_to 'Show', user %></td> <td><%= link_to 'Edit', edit_user_path(user) %></td> <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %> </tbody> </table> <%= paginate @users %> <!-- 追加箇所 --> |
これで5件づつ表示できるようになりました。
i18nで日本語化
config.i18n.default_locale = :jaを以下のあたりに記述します
1 2 3 4 5 6 7 8 9 |
module Remonote class Application < Rails::Application config.load_defaults 5.1 config.i18n.default_locale = :ja end end |
config/locales/ja.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
ja: helpers: page_entries_info: more_pages: display_entries: "<b>%{total}</b>中の%{entry_name}を表示しています <b>%{first} - %{last}</b>" one_page: display_entries: one: "<b>%{count}</b>レコード表示中です %{entry_name}" other: "<b>%{count}</b>レコード表示中です %{entry_name}" zero: "レコードが見つかりませんでした %{entry_name}" views: pagination: first: "« 最初" last: "最後 »" next: "次 ›" previous: "‹ 前" truncate: "…" |
はい、以上です!
最後までご覧いただき、ありがとうございました!😃