gpt4 book ai didi

activemodel - Rails Active Model 序列化程序未设置 root

转载 作者:行者123 更新时间:2023-12-02 17:43:28 24 4
gpt4 key购买 nike

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

在我的 Controller 中有这个

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

我的类(class)是这样的

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

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

end

我也试过在 Controller 中添加这个

 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} }

最佳答案

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

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

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

关于activemodel - Rails Active Model 序列化程序未设置 root,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17801861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com