5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Keisuke Death MarchAdvent Calendar 2023

Day 24

【kaminari】Rails APIで全体のページ数をレスポンスで返したい

Posted at

はじめに

Rails APIkaminari使用時に全体のページ数を取得してレスポンスしたかったので、その方法についてまとめます。

手順

再利用できるよう、consernsにモジュールとして切り出しておきます。
kaminariでは、Article.page(1).total_pagesのようにtotal_pagesを使うことで全体のページ数を取得することができます。

app/controllers/concerns/pagination.rb
module Pagination
  extend ActiveSupport::Concern

  def pagination(records)
    {
      total_pages: records.total_pages # 全体のページ数
    }
  end
end

meta: pagination(articles)paginationを呼び出し、metaキーを配下として値を時データを参照ができ、最終的にadapter: :jsonarticlesと一緒にレスポンスできるようにします。

class Api::V1::ArticlesController < Api::V1::BaseController
  include Pagination
  def index
    articles = Article.published.order(created_at: :desc).page(params[:page] || 1).per(10).includes(:user)
    render json: articles, meta: pagination(articles), adapter: :json
  end
end
レスポンス
{
  "articles": [
    {
      "id": 30,
      "title": "タイトル",
      "content": "本文",
    }
  ],
  "meta": {
    "total_pages": 3
  }
}
5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?