From 2678896a9ca5a0e563cb18233d7cb4ae6aaf8652 Mon Sep 17 00:00:00 2001 From: Edwin Lunando Date: Thu, 28 Jan 2016 13:51:19 +0700 Subject: [PATCH] update JSON adapter pagination links --- docs/howto/add_pagination_links.md | 36 ++++++++++++++---------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/docs/howto/add_pagination_links.md b/docs/howto/add_pagination_links.md index 64b903fb..b0552f4b 100644 --- a/docs/howto/add_pagination_links.md +++ b/docs/howto/add_pagination_links.md @@ -74,32 +74,30 @@ ActiveModelSerializers pagination relies on a paginated collection with the meth If you are using `JSON` adapter, pagination links will not be included automatically, but it is possible to do so using `meta` key. -In your action specify a custom serializer. -```ruby -render json: @posts, serializer: PaginatedSerializer, each_serializer: PostPreviewSerializer -``` +Add this method to your base API controller. -And then, you could do something like the following class. ```ruby -class PaginatedSerializer < ActiveModel::Serializer::CollectionSerializer - def initialize(object, options={}) - meta_key = options[:meta_key] || :meta - options[meta_key] ||= {} - options[meta_key] = { - current_page: object.current_page, - next_page: object.next_page, - prev_page: object.prev_page, - total_pages: object.total_pages, - total_count: object.total_count - } - super(object, options) - end +def pagination_dict(object) + { + current_page: object.current_page, + next_page: object.next_page, + prev_page: object.prev_page, + total_pages: object.total_pages, + total_count: object.total_count + } end ``` + +Then, use it on your render method. + +```ruby +render json: posts, meta: pagination_dict(posts) +``` + ex. ```json { - "articles": [ + "posts": [ { "id": 2, "title": "JSON API paints my bikeshed!",