0

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

render json: @resources

这会自动检测到资源有一个序列化程序,并使用它。

现在我想实现分页,我的想法是有一个名为 PaginatedResponse 的类,将其实例化并将其呈现为这样的 json:

render json: PaginatedResponse.new(@resources, <more meta information of the page>)

问题是,当我使用它时,一切正常,但资源不是使用 ActiveRecordSerializer 呈现的,而是使用默认的序列化程序。我怀疑这是因为 PaginatedResponse 没有扩展 ActiveRecord。

任何线索我该如何解决这个问题?

4

2 回答 2

0

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

于 2013-07-29T13:16:56.807 回答
0

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

这是为了用他的名字、电话、native_place 呈现所有用户。所以删除线

render json: @resources

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

于 2013-07-29T12:25:11.393 回答