Ruby on Railsを触ってみる ③kaminariでページネーション
1万件のツイートを表示するのに時間がかかりすぎてしまうので、ページネータというのを導入してみる。 kaminariというのが定番らしい。
Gemfileを編集。
$ git diff Gemfile diff --git a/Gemfile b/Gemfile index f1167d7..0b509d6 100644 --- a/Gemfile +++ b/Gemfile @@ -45,3 +45,6 @@ end # Use debugger # gem 'debugger', group: [:development, :test] + +# Pagenation +gem 'kaminari'
インストールする。
$ bundle install
kaminariのconfigファイルを生成する。
$ rails g kaminari:config
configファイルを編集して表示件数を100件ごとにしておく。 configration/initializers/kaminari_config.rbを編集。
Kaminari.configure do |config| # config.default_per_page = 100
controlerのインスタンス変数をセットするところを編集する。
$ git diff app/controllers/tweets_controller.rb diff --git a/app/controllers/tweets_controller.rb b/app/controllers/tweets_controller.rb index 6056733..0a17779 100644 --- a/app/controllers/tweets_controller.rb +++ b/app/controllers/tweets_controller.rb @@ -6,7 +6,7 @@ class TweetsController < ApplicationController # GET /tweets # GET /tweets.json def index - @tweets = Tweet.all + @tweets = Tweet.order(:id).page params[:page] end
viewファイルも編集する。テーブルの後ろにリンクを表示するためのメソッドを追加。
$ git diff app/views/tweets/index.html.erb diff --git a/app/views/tweets/index.html.erb b/app/views/tweets/index.html.erb index 5c61687..bb1469a 100644 --- a/app/views/tweets/index.html.erb +++ b/app/views/tweets/index.html.erb @@ -40,6 +40,4 @@ </tbody> </table> -<br> - -<%= link_to 'New Tweet', new_tweet_path %> +<%= paginate (@tweets) %>
これでこんな感じに。表示時間も気にならないぐらいに短縮された。 kaminariをBootstrapに対応させる。 Bootstrap用のViewを作成。
$ rails g kaminari:views bootstrap
それっぽくなったで。 とりあえずここまででコミット。 Pagenation twata701/twice GitHub