如何使用活动模型串行器自定义json-api序列化模型的ID?
问题描述:
我希望能够自定义在主动模型序列化JSON API使用适配器使用的ID。如何使用活动模型串行器自定义json-api序列化模型的ID?
即,我有其中被序列化不被认为是面向公众的各种原因的实际红宝石上轨道的ID用于特定模型的一个项目,但可替换的面向公众的唯一标识符是可用的。
我想利用这个标识符作为ID为JSON API序列化的内容,但我一直无法找出任何明显的方法来覆盖JSON API使用串行内的ID。
基本上,给出模型[{ id: 1, alt_id: '2aef7e'}, { id: 2, alt_id: '3b47c0' } ...]
我想一个方法来创建一个序列化版本:代替
{
"data":
[{
"id" : "2aef7e",
"type" : "my-model",
"attributes" : {...},
"relationships" : {...}
},{
"id" : "3b47c0",
"type" : "my-model",
"attributes" : {...},
"relationships" : {...}
}],
"included" : [ ... ]
}
:
{
"data":
[{
"id" : "1",
"type" : "my-model",
"attributes" : {...},
"relationships" : {...}
},{
"id" : "2",
"type" : "my-model",
"attributes" : {...},
"relationships" : {...}
}],
"included" : [ ... ]
}
但一直未能找到重写的明显的方法序列化的ID值。
答
您可以定义序列化中的一个方法,以避免使用对象的方法。
class MySerializer < ActiveModel::Serializer
attribute :id
def id
object.alt_id
end
end
+0
因此,对于我没有仔细阅读文档?尽管我仍然好奇为什么在某些示例中使用块('attribute(:name){'value'}')对':id'特别不适用。 – dgsan
(为什么'属性:id do ...'不工作?) – dgsan