【问题标题】:Rails Active Model serializers not setting rootRails Active Model 序列化程序未设置 root
【发布时间】:2013-07-23 05:06:09
【问题描述】:

我有一个不是 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} }

【问题讨论】:

    标签: activemodel active-model-serializers


    【解决方案1】:

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

    config/initializers/serializer.rb ActiveModel::Serializer.config.adapter = :json

    AMS documentation 声明这不向后兼容 0.9.x 和 0.8.x 版本。

    【讨论】:

      【解决方案2】:

      如果在控制器中使用 default_serializer_options 不起作用,也许您应该查看 config/initializers/wrap_parameters.rbinclude_root_in_json 选项。

      如果您对此感到好奇,可以在 here 找到有关该选项的源代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-03
        • 1970-01-01
        • 2014-06-10
        • 2015-09-18
        • 1970-01-01
        相关资源
        最近更新 更多