我有一些在/documents
路径中具有此结构的JSON(ID是UUID):
{
"tags": [
{
"id": "a33fc396-2428-11e3-8eeb-0800270f33f4",
"name": "test"
}
<more tags not shown>
],
"documents": [
{
"id": "c41460fa-2427-11e3-8702-0800270f33f4",
"name": "file.txt",
"tag_ids": [
"a33fc396-2428-11e3-8eeb-0800270f33f4"
]
}
<more documents not shown>
]
}
我们看到标签资源是旁加载的。 我正在使用 ember 数据使用以下路由加载 JSON:
App.Router.reopen
location: 'history'
rootURL: '/'
App.Router.map ->
@resource 'documents', ->
App.DocumentsRoute = Ember.Route.extend
model: ->
@get('store').findAll('document')
和型号:
App.Document = DS.Model.extend
name: DS.attr('string')
tags: DS.hasMany('tag')
App.Tag = DS.Model.extend
name: DS.attr('string')
这工作正常;我可以通过模板内的车把{{#each}}
块访问所有文档,并且可以验证是否可以访问属于给定单个文档的所有标签。
但是,我还希望在同一模板中访问所有标签的列表,而无需进入每个文档。 这应该不难,因为它作为旁加载的资源存在于 JSON 中,对吧? 除了我不知道该怎么做。 我已经在控制台中键入了各种内容,以查看它是否在控制器中的某个属性中,但我没有发现任何有希望的东西。 我猜我需要加载它并将其设置为控制器中的某些内容,但我不知道如何编写它。 我需要向代码中添加什么才能编写这样的东西?
{{#each tags}}
Name: {{name}} <--- should print "test"
{{/each}}
任何想法都值得赞赏!
因为您已经加载了所有标签,并且不想向 /tags
发送另一个请求。您可以使用 store.all('tags')
来获取已加载的标记:
App.DocumentsRoute = Ember.Route.extend({
model: function() {
var store = this.store;
return store.findAll('document').then(function(documents) {
// return an object with documents and tags, to be able to use both in the template
return {
documents: documents,
tags: store.all('tag') // to access all tags loaded in the payload we can just use store.all, so no additional request will be sent
}
});
}
});
在您的模板中:
{{#each documents}}
{{#each tags}}
Tags of that document
{{/each}}
{{/each}}
{{#each tags}}
All tags available
{{/each}}
你可以在那个小提琴 http://jsfiddle.net/marciojunior/v4aZj/中看到这一点
观察
在您的有效负载中,您必须tag_ids
这开ActiveModelAdapter
箱即用,如果您正在使用RESTAdapter
则需要更改为 tags
.