【问题标题】:activemodel serializer has_one with custom root name具有自定义根名称的 activemodel 序列化程序 has_one
【发布时间】:2014-08-07 09:17:34
【问题描述】:

我的序列化程序中有has_one 关系,但设置root: :some_other_root 似乎没有任何区别。我在文档中看到他们只使用了与has_many 不同的root 名称。所以问题是has_one 上是否可以有不同的根名称?

给定:

class UserSerializer < ActiveModel::Serializer
  attributes :id
  has_one :address, root: :primary_address
end

返回:

{"user":{"id": 12, "address":{"id":5,"company_name":"widgets co"}}}

预期:

{"user":{"id": 12, "primary_address":{"id":5,"company_name":"widgets co"}}}

【问题讨论】:

  • 试试key而不是root

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


【解决方案1】:

如果要将key 包含在用户属性中,请使用root,而不是root。 gem 存储库中有一个thorough explanation on how to embed associations。示例如下所示:

在序列化程序中: attribute :title, key: :name
#attributes: { name: 'Some Title' }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2020-02-15
    • 1970-01-01
    • 2018-04-04
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多