0
0

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 API】pagyを使用してページネーションを実装する方法

Last updated at Posted at 2025-01-27

pagyをインストールする

Gemfileに以下を追記します。

Gemfile
gem 'pagy', '~> 9.3' # omit patch digit

ターミナルでbundle installを実行します。

設定ファイルを作成する

上記のページからpagy.rbファイルをダウンロードし、config/initializersに保存します。

セットアップする

application_controller.rbに以下を追記します。

application_controller.rb
class ApplicationController < ActionController::API

  include Pagy::Backend

end

コントローラーを記述する

products_controller.rb

class ProductsController < ApplicationController

  def index
    @pagy, products = pagy(Product.all, limit: 10)
    render json: products
  end

end

ヘッダーを追加する

レスポンスヘッダーにcurrent-pagepage-itemstotal-pagestotal-countを追加するために以下の作業を行います。

config/initializers/pagy.rbの以下のコメントアウトを外します。

pagy.rb

require "pagy/extras/headers"
Pagy::DEFAULT[:headers] = { page: "Current-Page",
                            limit: "Page-Items",
                            count: "Total-Count",
                            pages: "Total-Pages" } # default

次にapplication_controller.rbに以下を追記します。

application_controller.rb
class ApplicationController < ActionController::API
  after_action { pagy_headers_merge(@pagy) if @pagy }

end

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?