【问题标题】:wrap attributes under custom key active model serializer在自定义键活动模型序列化程序下包装属性
【发布时间】:2023-04-06 12:37:02
【问题描述】:

我有类似的序列化器

class UserSeriazer < ActiveModel::Serializer
  attributes :name, :email
end

生成的json如下

{
  name: 'james'
  email: 'j@sample.com'
}

如何包装 above json 项,在自定义键下说 customer

{
  customer:
    {
      name: 'james'
      email: 'j@sample.com'
    }

}

我尝试了类似属性:name、:email、key::customer 之类的方法,但没有成功。提前致谢。

【问题讨论】:

    标签: ruby-on-rails active-model-serializers


    【解决方案1】:

    您可以尝试将根密钥添加到您的序列化程序文件中。在 UserSerializer 中,添加这个

    attributes :name, :email, root: 'customer'
    

    我不确定这将如何工作。如果这不起作用,您可以继续关注。

    最好的方法是创建一个名为 CustomerSerializer 的新序列化程序。这将继承自 UserSerializer。在派生的序列化程序中,您可以指定所需的属性。无论您在何处使用 UserSerializer,都应修改为使用 CustomerSerializer。

    class CustomerSerializer < UserSerializer
      attributes :name , :email
    end
    

    请评论哪个有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      相关资源
      最近更新 更多