我正在使用两种类型的端点编写API:单一和聚合。我有单个端点的RABL视图,如下所示:
# cat_view.json.rabl
object @cat
attributes :name
# dog_view.json.rabl
object @dog
attributes :name
这些工作正如预期的那样,但是我在聚合RABL视图中苦苦挣扎。我想要的JSON结构是:
{
'cats': {
'details': [{'name': 'Mittens'},
{'name': 'Mr. Wiskers'},
{'name': 'Crookshanks'}],
'count' : 3
},
'dogs': {
'details': [{'name': 'Rover'},
{'name': 'Fido'}],
'count' : 2
}
}
我当前的聚合RABL视图是:
# animals.json.rabl
child @cats do
collection @cats, :object_root => false
extends "cat_view"
end
node(:cat_count) { @cats.count }
child @dogs do
collection @dogs, :object_root => false
extends "dog_view"
end
node(:dog_count) { @dogs.count }
这导致了这个JSON:
{'cats': [{'name': Mittens'},
{'name': Mr. Wiskers'},
{'name': Crookshanks'}],
'cat_count': 3,
'dogs': [{'name': 'Rover'},
{'name': 'Fido'}],
'dog_count': 2}
我的问题:
为了获得上述JSON结构,我的animals.json.rabl
应如何查看?
答案 0 :(得分:2)
要添加details
密钥,请为现有child @cats
块details
命名:
child @cats => :details do
collection @cats, :object_root => false
extends "cat_view"
node(:count) { @cats.count }
end
对于问题的嵌套部分,您可以通过创建一个新的换行子块来执行此操作:
# animals.json.rabl
child :cats do
child @cats => :details do
collection @cats, :object_root => false
extends "cat_view"
node(:count) { @cats.count }
end
end
child :dogs do
child @dogs => :details do
collection @dogs, :object_root => false
extends "dog_view"
node(:count) { @dogs.count }
end
end