Ruby on rails 在RubyonRails4API中实现分页

Ruby on rails 在RubyonRails4API中实现分页,ruby-on-rails,Ruby On Rails,我正在Rails上构建一个API,使用ActiveRecordSerializer进行序列化。当我想要呈现我使用的资源列表时: render json: @resources 这会自动检测资源是否存在序列化程序,并使用它 现在我想实现分页,我的想法是创建一个名为PaginatedResponse的类,实例化它并将其呈现为json,如下所示: render json: PaginatedResponse.new(@resources, <more meta information of t

我正在Rails上构建一个API,使用ActiveRecordSerializer进行序列化。当我想要呈现我使用的资源列表时:

render json: @resources
这会自动检测资源是否存在序列化程序,并使用它

现在我想实现分页,我的想法是创建一个名为PaginatedResponse的类,实例化它并将其呈现为json,如下所示:

render json: PaginatedResponse.new(@resources, <more meta information of the page>)
呈现json:PaginatedResponse.new(@resources,) 问题是,当我使用它时,一切都很好,但资源不是使用ActiveRecordSerializer呈现的,而是使用默认序列化程序呈现的。我怀疑这是因为PaginatedResponse没有扩展ActiveRecord


有什么线索可以解决这个问题吗?

Rails 4在默认情况下引入了一个新概念jbuilder。因此,只需创建index.json.jbuilder并放入基于json syntex的代码。只需参考下面的默认脚手架索引json jbuilder

json.array!(@users) do |user|
  json.extract! user, :name, :email, :phone, :native_place
  json.url user_url(user, format: :json)
end
这用于呈现所有用户的姓名、电话、出生地。 因此,请删除该行

render json: @resources

从您的代码和实现新的jbuilder概念。

解决方案在PaginatedResponse中包括ActiveModel::SerializerSupport,以指示应使用序列化程序的ActiveRecordSerializer。

我需要类似的解决方案,您能否发布PaginatedResponse类和所用序列化程序的一些代码示例。我似乎不知道如何获取对象数组的根来反映我的资源类。谢谢