2

我有一个不是 ActiveRecord 对象的类,我试图为它创建一个 AM 序列化程序。我可以返回正确的 json,但它不包括根

在我的控制器中有这个

format.json { render json: @current_user, root: "current_user" }

我的课看起来像这样

class CurrentUser 
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :first_name, :last_name, :user_type, :user_id

end

我也尝试在控制器中添加它

 def default_serializer_options
  {root: true}
 end

但是我的 json 对象仍然没有 Ember 模型所需的根

返回对象

{"first_name":"Luke","last_name":"Skywalker","user_type":"Padawan","user_id":12}

我需要

{current_user: {"first_name":"Luke","last_name":"Skywalker","user_type":"Padawan","user_id":12} }
4

2 回答 2

5

对于将来可能遇到同样问题的任何人,在使用ActiveModelSerializers 0.10.x时,只需添加到现有初始化程序或创建一个新初始化程序并将其添加到您的响应中包含根节点:

配置/初始化程序/serializer.rb ActiveModel::Serializer.config.adapter = :json

AMS 文档指出,这不向后兼容 0.9.x 和 0.8.x 版本。

于 2016-02-10T03:09:27.730 回答
1

如果default_serializer_options在您的控制器内部使用不起作用,也许您应该查看一下config/initializers/wrap_parameters.rb选项include_root_in_json

如果您好奇,可以在此处找到该选项的相关源代码。

于 2013-07-31T19:37:42.420 回答