我正在使用Ruby on Rails 4和RABL gem。我想通过从index.json.rabl
中呈现show.json.rabl
视图来重用模板,并保持jsonapi.org(来源:RABL文档)中规定的约定。
也就是说,我有以下文件:
# 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","...":...}]}
这里有一个简洁的方法:
<标题>/base.rabl:attributes :id, :title
child(:another_child, :object_root => false) { attributes :id, :title }
<标题>/show.rabl: object @thing
extends 'things/base'
<标题>/index.rabl: collection @things
extends 'things/base'
标题>标题>标题>
可以使用extends - https://github.com/nesquena/rabl/wiki/Reusing-templates
object @post
child :categories do
extends "categories/show"
end
我在解释我需要从https://github.com/nesquena/rabl/wiki/Reusing-templates做什么时遇到了麻烦,但最终弄清楚了。对于我来说,我的文件结构是这样的:(更改名称以保护无辜;))
/app/controllers/api/my/boring_things_controller.rb
/app/views/api/my/boring_things/index.json.rabl
/app/controllers/api/my/interesting_things_controller.rb
/app/views/api/my/interesting_things/index.json.rabl
boring_things/index.json。rabl看起来像这样(除了真实的,它有更多的属性):
collection @boring_things, :root => :things, :object_root => false
attributes :id,
:name,
:created_at,
:updated_at
和 interesting_things/index.json。看起来几乎相同
collection @interesting_things, :root => :things, :object_root => false
attributes :id,
:name,
:created_at,
:updated_at
我只想重用属性部分。关于https://github.com/nesquena/rabl/wiki/Reusing-templates让我困惑的部分是,我并不认为我真的需要一个"节点",我也不认为我需要一个"子",因为我希望属性在顶层,而不是作为一个子对象。但事实证明我确实需要"孩子"。下面是我最后写的:
/app/controllers/api/my/boring_things_controller.rb
/app/views/api/my/boring_things/index.json.rabl
/app/controllers/api/my/interesting_things_controller.rb
/app/views/api/my/interesting_things/index.json.rabl
/app/views/api/my/shared/_things.json.rabl
_things.json。rabl是:
attributes :id,
:name,
:created_at,
:updated_at
boring_things/index.json。rabl现在是:
child @boring_things, :root => :things, :object_root => false do
extends "api/my/shared/_things"
end
和 interesting_things/index.json。rabl现在是:
child @interesting_things, :root => :things, :object_root => false do
extends "api/my/shared/_things"
end
所以对你来说,而不是呈现显示从索引,我会尝试做一些事情,你提取的文章属性到索引和显示共享的rabl文件。在show.json所在的目录中。rabl和index.json。rabl是(我假设它的视图/文章/index.json。rabl和views/articles/show.json.rabl),创建一个"_article_attributes.json"。rabl "文件。抱歉,我没有你的确切设置,所以我不能在语法上亲自尝试,但它应该是这样的在你的index.json.rabl:
child @articles do
extends "articles/_article_attributes"
end
旁注:当我这样做时,另一件让我绊倒的事情是,由于我的共享文件位于使用它们的不同rabl文件的兄弟目录中,并且我试图使用相对路径,但这不起作用。相反,我不得不使用从"app/views"下开始的路径。"扩展'api/my/shared/_things'"而不是"扩展'../shared/_things'")。这是一种奇怪的情况,我不会详细说明为什么这样做,但如果可以的话,最好将共享文件放在与索引和显示相同的目录中,就像你所做的那样