1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】kaminari

Posted at

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。

Rails アプリを作っていると、生徒一覧や記事一覧のようにデータがどんどん増えていく場面があります。
そんなときに便利なのが ページネーション (pagination)。これを簡単に実装できるのが Kaminari という Gem です。


📦 Kaminari とは?

Kaminari は、Rails で人気のある ページネーション用 Gem です。データを「1 ページあたり ○ 件」と区切り、ページを移動できる仕組みを提供してくれます。

例:

  • /students?page=1 → 1 ページ目(10 件表示)
  • /students?page=2 → 2 ページ目(次の 10 件表示)

⚙️ 導入方法

Gem の追加

Gemfile
gem 'kaminari'
$ bundle install

コントローラ

class StudentsController < ApplicationController
  def index
    @students = Student.page(params[:page]).per(10)
  end
end

ビュー(ERB の場合)

<%= paginate @students %>

これだけでページ送りができるようになります!


🔍 よく使うメソッド

students = Student.page(2).per(5)

students.current_page # => 2
students.limit_value  # => 5(1ページあたりの件数)
students.total_pages  # => 総ページ数
students.total_count  # => 全件数

🎨 デザインとの統合

Bootstrap などの UI フレームワークとも簡単に連携できます。

$ rails g kaminari:views bootstrap4

これで Bootstrap 風のページネーションビューが生成されます。


✅ まとめ

  • Kaminari は Rails で使える定番のページネーション Gem
  • .page(params[:page]).per(10) でサクッと使える
  • paginate @records でページリンクを表示できる
  • UI フレームワークとも連携可能
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?