LoginSignup
190
183

More than 5 years have passed since last update.

【Ruby on Rails】gem(Kaminari)でページネーション機能を追加してBootstrapを適用する。

Last updated at Posted at 2017-04-08

はじめに

アイテム一覧画面に表示されるアイテム数が増えるにつれ、スクロールするのが大変/見づらいので、指定したアイテム数毎に、複数ページに分けて表示されるようにします。
今回はkaminariというgemを使ってこれを実現して行きます。

ページネーションを追加する前
スクリーンショット 2017-04-08 19.52.13.png

ページネーションを追加した後
スクリーンショット 2017-04-08 22.58.33.png

追記(2019/02/02)

個人的にはmislav/will_paginateの方が導入が簡単な印象を受けたので一応名前だけ紹介しときます。どんな感じかはRuby on Rails チュートリアル:実例を使って Rails を学ぼう > 10.3.3 ページネーションが分かり易い気がします。

ページネーション機能を追加する

はじめに、「Gemfile」に以下を追記し、bundle installします。

Gemfile
gem 'kaminari', '~> 0.17.0'

Rails5系を使用しているため、バージョン0.17.0を指定しています。

$ bundle install

次に、「app/controllers/welcome_controller.rb」を編集します。

welcome_controller.rb(編集前)
class WelcomeController < ApplicationController
  PER = 8

  def index
    @words = Word.all
  end
end
welcome_controller.rb(編集後)
class WelcomeController < ApplicationController
  PER = 8

  def index
    @words = Word.page(params[:page]).per(PER)
  end
end

最後に、「app/views/welcome/index.html.erb」を編集します。

app/views/welcome/index.html.erb(編集前)
<div class="page-header">
  <h1>単語一覧</h1>
</div>
<div class="list-group">
  <% @words.each do |word| %>
    <%= link_to(word, class: 'list-group-item') do %>
      <h4 class="list-group-item-heading">
        <%= word.word %>
      </h4>
      <p class="list-group-item-text">
        <%= word.reading %>
      </p>
    <% end %>
  <% end %>
</div>
app/views/welcome/index.html.erb(編集後)
<div class="page-header">
  <h1>単語一覧</h1>
</div>
<div class="list-group">
  <% @words.each do |word| %>
    <%= link_to(word, class: 'list-group-item') do %>
      <h4 class="list-group-item-heading">
        <%= word.word %>
      </h4>
      <p class="list-group-item-text">
        <%= word.reading %>
      </p>
    <% end %>
  <% end %>
  <%= paginate @words %>
</div>

追記したのは、<%= paginate @words %>だけです。以上でページネーションが出来上がったかと思います。

スクリーンショット 2017-04-08 19.51.35.png

Bootstrapに合わせる

Bootstrap用にカスタマイズすることもできます。
まずは、Gemfileにkaminari-bootstrapというgemを追記し、bundle installします。

Gemfile
gem 'kaminari-bootstrap', '~> 3.0.1'

$ bundle install

そして最後に、i18nの設定を追加すれば完了です。
「config/locales/kaminari_ja.yml」を追加し、以下を書き込みます。

config/locales/kaminari_ja.yml
ja:
  views:
    pagination:
      first: "&laquo; 最初"
      last: "最後 &raquo;"
      previous: "&lsaquo; 前"
      next: " &rsaquo;"
      truncate: "..."

最後に

上記の手順後、うまく表示されない場合は、一度「rails s」を終了し、再起動してみてください。

190
183
1

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
190
183