LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】bootstrapでページネーション機能を作成する

Last updated at Posted at 2019-10-12

gemのインストール

kaminariのgemをインストールします。

gem 'kaminari'
gem 'kaminari-bootstrap', '~> 3.0.1' #bootstrap3用
$ bundle install

インストール後、サーバーを再起動します。

ymlファイルの作成

config/localeskaminari_ja.ymlを作成し、以下を記載します。

kaminari_ja.yml
ja:
  views:
    pagination:
      first: "« 最初"
      last: "最後 »"
      previous: "‹ 前"
      next: " ›"
      truncate: "..."

コントローラーの変更

class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

以下のように変更します。

PER = 5  #区切りたいところを決める

class PostsController < ApplicationController
  def index
    @posts = Post.page(params[:page]).per(PER)
  end

ビューの変更

挿入したい箇所に以下を記入します。

    <div class="paginate text-center">
      <%= paginate @like_posts %>
    </div>

追記:中央寄せ

自動でpagenationクラスが作成されますので
以下の方法で、中央寄せ出来ます。


.pagination {
  justify-content: center;
}

完成

image.png

以上で、ページネーション機能が作成出来ます!

0
0
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
0
0