The Pageable
concern provides a method to paginate the records in a controller's action.
The method paginate
is used to paginate the records.
It will use the query parameters page
and per_page
to paginate the records.
class UsersController < ApplicationController
include Warped::Controllers::Pageable
def index
users = paginate(User.all)
render json: users, meta: pagination
end
end
Request examples:
GET /users?page=1&per_page=10 # returns the first page of users with 10 records per page
GET /users?per_page=25 # returns the first page of users with 25 records per page
GET /users?page=2&per_page=25 # returns the second page of users with 25 records per page
The pagination
method can be used to access the pagination information.
class UsersController < ApplicationController
include Warped::Controllers::Pageable
def index
users = paginate(User.all)
render json: users, meta: pagination
end
end
pagination
returns a hash with
page
- the current pageper_page
- the number of records per pagetotal_pages
- the total number of pagestotal_count
- the number of records in the scopenext-page
- the next page numberprev-page
- the previous page number
By default, the paginate
method will paginate the scope in pages of size 10, and will return the first page if the page
query parameter is not provided.
Additionally, there's a limit of 100
records per page. So, if the per_page
query parameter is greater than 100
, the pagination will use 100
as the page size.
You can customize the default page size and the default page number by overriding the default_per_page
value in the controller.
class UsersController < ApplicationController
include Warped::Controllers::Pageable
# This will set the default page size to 25 when the `per_page` query parameter is not provided
self.default_per_page = 25
def index
users = paginate(User.all)
render json: users, meta: pagination
end
end