我的序列化程序中有一个 has_one
关系,但设置 root::some_other_root
似乎没有任何区别。我在文档中看到他们只使用了不同的 root
名称和 has_many
。所以问题是 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
将作为用户属性的一部分包含在内,则使用 key
而不是 root
。有一个 thorough explanation on how to embed associations在 gem repo 中。该示例如下所示:
In Serializer:
attribute :title, key: :name
#attributes:{ name: 'Some Title' }
关于ruby-on-rails - 具有自定义根名称的 activemodel 序列化器 has_one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25178647/