12
12

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 5 years have passed since last update.

Grape+KaminariでAPIのページング対応

Posted at

kaminari https://github.com/amatsuda/kaminari というgemを使うことにした。

bundle installしてrails g。

gem 'kaminari'
bundle install
rails g kaminari:config

モデルクラスに一度のリクエストで出力する数を設定しておく。

class Post < ActiveRecord::Base

  paginates_per 5
  ...

end

あとはこんな感じでModel.query().page(params[:page])をつけて書くだけ。
Model.query().page(params[:page]).per(10)見たいな形でモデルに設定した値でなくても取って来れるので、offset,limitみたいな使い方も簡単。

# coding: utf-8
class Post_API < Grape::API
  resource :posts do

    # http://localhost:3000/api/v1/posts
    params do
      optional :page, type: Integer, desc: "Page Num"
    end

    get do
      Post.where(published: true).page(params[:page])
    end

  end
end
12
12
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
12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?