LoginSignup
26
24

More than 3 years have passed since last update.

Ruby on Rails ページネーション

Last updated at Posted at 2018-09-29

実装する時に調べましたが、情報が散っていたので自分用にまとめておきます。

環境

AWS Cloud9
ruby 2.4.1
rails 5.1.4

Gemの設定

使用するライブラリは、
will_paginate
bootstrap-will_paginate
Rails Tutorialにて紹介されていたので採用しました。
他にはKaminariとかもページネーションとしては情報が多いです。

Gemfileに追加します。

Gemfile
gem 'will_paginate',           '3.1.6'
gem 'bootstrap-will_paginate', '1.0.0'

追加したら$ bundle installを実行します。

Controllerの設定

モデル名.paginateでページネーションを扱えました
インスタンス変数に代入しています。

users_controller.rb
def index
  @users = User.paginate(page: params[:page])
end

ページ毎の件数を指定したい

デフォルトでは30件のようです。
引数に:per_pageオブションを追加することで設定できました。

users_controller.rb
def index
  # 20件毎に表示したい場合
  @users = User.paginate(page: params[:page], per_page: 20)
end

Viewの設定

ページネーションを表示したいviewで下記を設定して完了しました。

index.html.erb
<%= will_paginate @users %>
<!-- 下記でも表示された -->
<%= will_paginate %>
# 下記のエラーが発生する場合は、サーバーを再起動することで症状が改善されるかもしれません。
undefined method paginate

ラベルを日本語化したい

設定していないと、ラベルが英語表記になるので、必要なら日本語化します。
config/environment.rb に以下を追加すると、設定を上書きできます。

config/environment.rb
# 記号( < と > )も入るので不要なら消す。
WillPaginate::ViewHelpers.pagination_options[:previous_label] = '&lt 前へ'
WillPaginate::ViewHelpers.pagination_options[:next_label] = '次へ &gt'

個別に表示したい場合は、直に記述も可能です。
一部のビューのみ変更したい場合に使えそう。

index.html.erb
<%= will_paginate @users, previous_label: '&lt 前へ', next_label: '次へ &gt' %>

i18nの設定を:jaにしているならlocalsファイルで設定することもできるみたいです。

config/application.rb
config.i18n.default_locale = :ja
config/locals/ja.yml
ja:
  will_paginate:
    previous_label: 
    next_label: 
    page_gap: 
26
24
3

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
26
24