[英]JSON API style sideloading in Rails ActiveModel::Serializers
I'm trying to build a JSON API style API using AM::Serializer. 我正在尝试使用AM :: Serializer构建JSON API样式的API。 I'm running into an issue with sideloading.
我遇到了侧载问题。
I want to be able to build JSON that looks like: 我希望能够构建如下所示的JSON:
{
"primaries": [{
"id": 123,
"data": "Hello world.",
"links": {
"secondaries": [ 1, 2, 3 ]
}
}],
"linked" : {
"secondaries": [
{
"id": 1,
"data": "test1"
},
{
"id": 2,
"data": "test2"
},
{
"id": 3,
"data": "test3"
}
]
}
}
The code I've been able to come up with looks like: 我已经想出的代码如下:
class PrimarySerializer < ActiveModel::Serializer
attributes :id, :data
has_many :secondaries, key: :secondaries, root: :secondaries
embed :ids, include: true
end
Which generates JSON that looks like: 生成如下所示的JSON:
{
"primaries": [{
"id": 123,
"data": "Hello world.",
"secondaries": [ 1, 2, 3 ]
}],
"secondaries": [
{
"id": 1,
"data": "test1"
},
{
"id": 2,
"data": "test2"
},
{
"id": 3,
"data": "test3"
}
]
}
Is there a way to override the location of the in-element secondaries
and sideloaded secondaries
such that they live in child nodes link
and linked
? 有没有办法覆盖的元件中的位置,
secondaries
和侧载secondaries
使得他们生活在子节点link
和linked
?
The above code is an abstraction of the actual code and may not work. 上面的代码是实际代码的抽象,可能无法正常工作。 Hopefully it illustrates the point sufficiently.
希望它能充分说明这一点。
Thanks! 谢谢!
ActiveModel Serializers can do this. ActiveModel序列化程序可以做到这一点。 The problem is that the built-in association methods are to restrictive.
问题在于内置的关联方法是限制性的。 Instead you must build up the
links
& linked
parts manually. 相反,您必须手动建立
links
和linked
部分。
(This answer refers to the stable 0.8.1 version of ActiveModel Serializers ) (此答案指的是稳定的ActiveModel Serializers 0.8.1版本 )
Here's a Gist with a complete JSON-API solution https://gist.github.com/mars/97a637560109b8ddfb27 这是具有完整JSON-API解决方案的Gist https://gist.github.com/mars/97a637560109b8ddfb27
Example: 例:
class ExampleSerializer < JsonApiSerializer # see Gist for superclass
attributes :id, :name, :links
def links
{
things: object.things.map(&:id),
whatzits: object.whatzits.map(&:id)
}
end
def as_json(*args)
hash = super(*args)
hash[:linked] = {
things: ActiveModel::ArraySerializer.new(
object.things,
each_serializer: ThingsSerializer
).as_json,
whatzits: ActiveModel::ArraySerializer.new(
object.whatzits,
each_serializer: WhatzitsSerializer
).as_json
}
hash
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.