LoginSignup
10
11

More than 5 years have passed since last update.

Railsでページャーを簡単に実装できるGem「kaminari」

Last updated at Posted at 2014-12-22

いつ使えるの?

Railsプロジェクトで、ページャーを実装したい時。

公式リポジトリ

kaminari

kaminariをインストール

Gemfile
gem 'kaminari'
$ bundle install --path vendor/bundle

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

設定ファイルを生成

$ bundle exec rails g kaminari:config
config/initializers/kaminari_config.rb
Kaminari.configure do |config|
  config.default_per_page = 5
  # 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
end

default_per_page には、ページに表示するコンテンツの数を指定します。(Controller側で、Book.page(params[:page]).per(5)とも書ける)

Bookモデルを作成

$ bundle exec rails g model book title:string color:string

Controllerを編集

app/controllers/home_controller.rb
def show
  @books = Book.page(params[:page])
end

View側

app/views/home/show.html.erb

<% @books.each do |book| %>
<%= book.title %>
<% end %>
<%= paginate(@books) %>

page.png

データをいれると、コンテンツが表示されて、paginateの部分にページャーができました。

シンプル!

10
11
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
10
11