我正在使用rubyonrails4和RABLgem。我想通过从show.json.rabl
中呈现index.json.rabl
视图来重用模板,并在jsonapi.org中保持约定(源代码:RABL documentation)。
也就是说,我有以下文件:
# index.json.rabl
collection @articles => :articles
attributes :id, :title, :...
# show.json.rabl
collection [@article] => :articles
attributes :id, :title, :...
因为对于每个
article
实例,index.json.rabl
呈现的属性与show.json.rabl
相同,所以我希望将后者作为部分模板重用,或者(可能)扩展第一个模板。我想输出的是:
# index JSON output
{"articles":[{"id":1,"title":"Sample 1","...":...},{"id":2,"title":"Sample 2","...":...},{"id":3,"title":"Sample 3","...":...}]}
# show JSON output
{"articles":[{"id":1,"title":"Sample 1","...":...}]}
最佳答案
这里有一个简单的方法:
物品/基地.rabl:
attributes :id, :title
child(:another_child, :object_root => false) { attributes :id, :title }
事物/表演.rabl:
object @thing
extends 'things/base'
事物/索引.rabl:
collection @things
extends 'things/base'