活动模型序列化程序分页链接未显示

时间:2016-05-01 00:38:46

标签: ruby-on-rails active-model-serializers

我正在使用此处的说明:https://github.com/rails-api/active_model_serializers/blob/master/docs/howto/add_pagination_links.md

我有一个初始化文件:

ActiveModelSerializers.config.adapter = :json_api

(重启服务器进行初始化)

在我的模特中,我有:

def packages
    @user = User.find(params[:id])
    @records = @user.get_records("api").paginate(page: params[:page], per_page: 3)
    render json: @records
end

我的回复如下,并没有显示链接块:

[
  {
    created_at: "2016-04-07T18:24:03.216Z",
    title: "Record 1"
  },
  {
    created_at: "2016-03-07T18:24:43.245Z",
    title: "Record 2"
  },
  {
    created_at: "2016-02-07T18:22:33.236Z",
    title: "Record 3"
  }
]

我可以在服务器日志中看到它正在使用will_paginate:

[active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with WillPaginate::Collection (0.13ms)

为什么我没有看到链接的任何想法?

更新

我使用will_paginate对数组进行分页,因此我在控制器中添加了require'will_paginate / array'。 当我尝试按照第二种方法在控制器中创建字典时,就像这样......

class Api::V1::UsersController < ActionController::Base
  require 'will_paginate/array'
  def packages
      @user = User.find(params[:id])
      @records = @user.get_records("api").paginate(page: params[:page], per_page: 3)
      render json: @records, 
      meta: pagination_dict(@records)
  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
end

然后我得到:

undefined method `prev_page' for #<WillPaginate::Collection:0x007fced3698d78> Did you mean? previous_page per_page

我觉得这也很奇怪。

1 个答案:

答案 0 :(得分:0)

函数pagination_dict(object)应位于Base控制器中,而不应位于U​​sers Controller