Get kaminari pagination links in the JSON generated by the active model serializer
Asked Answered
B

2

3

I am trying to convert @admins to JSON using the AdminSerializer

#app/serializers/admin_serializer.rb
class AdminSerializer < ActiveModel::Serializer
  attributes :id, :email, :access_locked?
end

where Admins is>> @admins = @search.result(:distinct => true).page(params[:page][:number]).per(10) and @search = Admin.search(params[:q])

When I execute this command>> ActiveModel::SerializableResource.new(@admins.to_a).as_json I do get the desired JSON, but the pagination links are missing from the JSON received, as they were lost while converting the @admins to array using to_a. However, when I execute render :json => @admins , I get the complete JSON with the pagination links in it, as shown inn the screenshot below: enter image description here

Bellini answered 30/3, 2016 at 6:38 Comment(0)
P
4

In the latest commit available you need to use:

resource = ActiveModel::SerializableResource.new(@admins)
resource.to_json(serialization_context: ActiveModelSerializers::SerializationContext.new(request))
Pignus answered 30/3, 2016 at 13:38 Comment(1)
One more doubt that I have is, @admins_json = ActiveModel::SerializableResource.new(@admins.to_a).as_json is returning me a JSON, while the method described above gives a string, which I have to parse using JSON.parse() of javascript. do I have to call to_json again to convert it into a JSON?Bellini
H
2

I used kaminari it's great pagination gem and i cant add paginataion in json response but i found and custom code.

#your controller#index
require 'pagination'
...your code
render json: Pagination.build_json(@posts, @comment_page, @comment_per)

# /lib/pagination.rb
class Pagination
  def self.build_json object, nested_page = 1, nested_per = 10
    ob_name = object.name.downcase.pluralize
    json = Hash.new
    json[ob_name] = ActiveModelSerializers::SerializableResource.new(object.to_a, nested_page: nested_page, nested_per: nested_per)
    json[:pagination] = {
        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
    }
    return json
  end
end
Haldes answered 29/1, 2020 at 22:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.