update JSON adapter pagination links

This commit is contained in:
Edwin Lunando 2016-01-28 13:51:19 +07:00
parent 58ff7535b7
commit 2678896a9c

View File

@ -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. 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. Add this method to your base API controller.
```ruby
render json: @posts, serializer: PaginatedSerializer, each_serializer: PostPreviewSerializer
```
And then, you could do something like the following class.
```ruby ```ruby
class PaginatedSerializer < ActiveModel::Serializer::CollectionSerializer def pagination_dict(object)
def initialize(object, options={}) {
meta_key = options[:meta_key] || :meta current_page: object.current_page,
options[meta_key] ||= {} next_page: object.next_page,
options[meta_key] = { prev_page: object.prev_page,
current_page: object.current_page, total_pages: object.total_pages,
next_page: object.next_page, total_count: object.total_count
prev_page: object.prev_page, }
total_pages: object.total_pages,
total_count: object.total_count
}
super(object, options)
end
end end
``` ```
Then, use it on your render method.
```ruby
render json: posts, meta: pagination_dict(posts)
```
ex. ex.
```json ```json
{ {
"articles": [ "posts": [
{ {
"id": 2, "id": 2,
"title": "JSON API paints my bikeshed!", "title": "JSON API paints my bikeshed!",