mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
update JSON adapter pagination links
This commit is contained in:
parent
58ff7535b7
commit
2678896a9c
@ -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!",
|
||||
|
||||
Loading…
Reference in New Issue
Block a user