【问题标题】:Get kaminari pagination links in the JSON generated by the active model serializer获取活动模型序列化程序生成的 JSON 中的 kaminari 分页链接
【发布时间】:2016-07-18 00:30:03
【问题描述】:

我正在尝试使用 AdminSerializer 将 @admins 转换为 JSON

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

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

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

【问题讨论】:

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


    【解决方案1】:

    latest commit可用你需要使用:

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

    【讨论】:

    • 我还有一个疑问是,@admins_json = ActiveModel::SerializableResource.new(@admins.to_a).as_json 正在返回一个 JSON,而上述方法给出了一个字符串,我必须使用 javascript 的 JSON.parse() 解析它。我是否必须再次调用 to_json 才能将其转换为 JSON?
    【解决方案2】:

    我使用了 kaminari,它是很棒的分页宝石 我不能在 json 响应中添加分页 但我找到了自定义代码。

    #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
    

    【讨论】:

      猜你喜欢
      • 2016-05-01
      • 2018-02-04
      • 1970-01-01
      • 2017-01-14
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多