获取活动模型序列化程序

时间:2016-03-30 06:38:57

标签: json ruby-on-rails-4 kaminari active-model-serializers json-api

我正在尝试使用AdminSerializer

将@admins转换为JSON
#app/serializers/admin_serializer.rb
class AdminSerializer < ActiveModel::Serializer
  attributes :id, :email, :access_locked?
end

其中管理员是&gt;&gt; @admins = @search.result(:distinct => true).page(params[:page][:number]).per(10)@search = Admin.search(params[:q])

执行此命令时&gt;&gt; ActiveModel::SerializableResource.new(@admins.to_a).as_json我确实获得了所需的JSON,但收到的JSON中缺少分页链接,因为在使用@adminsto_a转换为数组时丢失了这些链接。 但是,当我执行render :json => @admins时,我会获得带有分页链接的完整JSON,如下面的屏幕截图所示: enter image description here

2 个答案:

答案 0 :(得分:3)

在可用的latest commit中,您需要使用:

resource = ActiveModel::SerializableResource.new(@admins)
resource.to_json(serialization_context: ActiveModelSerializers::SerializationContext.new(request))

答案 1 :(得分:0)

我用kaminari这是很棒的分页宝石 我无法在json响应中添加paginataion 但是我找到了自定义代码。

#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