|
1 | 1 | # How to add pagination links
|
2 | 2 |
|
3 |
| -Pagination links will be included in your response automatically as long as the resource is paginated and if you are using a ```JSON-API``` adapter. The others adapters does not have this feature. |
| 3 | +### JSON-API adapter |
| 4 | + |
| 5 | +Pagination links will be included in your response automatically as long as the resource is paginated and if you are using a ```JSON-API``` adapter. |
4 | 6 |
|
5 | 7 | If you want pagination links in your response, use [Kaminari](https://github.com/amatsuda/kaminari) or [WillPaginate](https://github.com/mislav/will_paginate).
|
6 | 8 |
|
|
44 | 46 | ```
|
45 | 47 |
|
46 | 48 | AMS relies on either [Kaminari](https://github.com/amatsuda/kaminari) or [WillPaginate](https://github.com/mislav/will_paginate). Please install either dependency by adding one of those to your Gemfile.
|
| 49 | + |
| 50 | +### JSON adapter |
| 51 | + |
| 52 | +If you are using `JSON` adapter, pagination links will not be included automatically, but it is possible to do so using `meta` key. |
| 53 | + |
| 54 | +In your action specify a custom serializer. |
| 55 | +```ruby |
| 56 | +render json: @posts, serializer: PaginatedSerializer, each_serializer: PostPreviewSerializer |
| 57 | +``` |
| 58 | + |
| 59 | +And then, you could do something like the following class. |
| 60 | +```ruby |
| 61 | +class PaginatedSerializer < ActiveModel::Serializer::ArraySerializer |
| 62 | + def initialize(object, options={}) |
| 63 | + meta_key = options[:meta_key] || :meta |
| 64 | + options[meta_key] ||= {} |
| 65 | + options[meta_key] = { |
| 66 | + current_page: object.current_page, |
| 67 | + next_page: object.next_page, |
| 68 | + prev_page: object.prev_page, |
| 69 | + total_pages: object.total_pages, |
| 70 | + total_count: object.total_count |
| 71 | + } |
| 72 | + super(object, options) |
| 73 | + end |
| 74 | +end |
| 75 | +``` |
| 76 | +ex. |
| 77 | +```json |
| 78 | +{ |
| 79 | + "articles": [ |
| 80 | + { |
| 81 | + "id": 2, |
| 82 | + "title": "JSON API paints my bikeshed!", |
| 83 | + "body": "The shortest article. Ever." |
| 84 | + } |
| 85 | + ], |
| 86 | + "meta": { |
| 87 | + "current_page": 3, |
| 88 | + "next_page": 4, |
| 89 | + "prev_page": 2, |
| 90 | + "total_pages": 10, |
| 91 | + "total_count": 10 |
| 92 | + } |
| 93 | +} |
| 94 | +``` |
| 95 | + |
| 96 | +### FlattenJSON adapter |
| 97 | + |
| 98 | +This adapter does not allow us to use `meta` key, due to that it is not possible to add pagination links. |
0 commit comments