我有一个模型,Post
有很多Comment
个。 GET /posts/12
的响应非常符合Ember-Data:
{
"post": {
"id": 12,
"title": "I Love Ramen",
"created_at": "2011-08-19T14:22",
"updated_at": "2011-08-19T14:22",
"body": "..."
}
}
Post
的{{1}}的API为Comment
,返回
GET /posts/12/comments
我可以对我的模型或我的适配器做些什么来告诉它,对于{
"comments": [
{
"id": 673,
"author_id": 48,
"created_at": "2011-08-21T18:03",
"body": "Me too!"
}
]
}
的{{1}},请使用Post 12
?请注意,Comment
本身并不了解/posts/12/comments
ID。
回应buuda's answer,这里有一些澄清:
Post
必须能够查找其Comment
,以便我可以(a)显示Post
上的评论和(b){{1}上的属性喜欢
Comment
如果我必须实现PostRoute
计算属性,那对我来说没问题。在上述答案中,buuda建议
Post
如何让数据存储区取代hasComments: function() {
return this.get('comments.length') > 0;
}.property('comments')
而不是comments
?
答案 0 :(得分:2)
您无需在模型之间设置任何关系。嵌套资源允许您获取适当的数据。使用此路由器:
App.Router.map(function() {
this.resource('posts', { path: '/posts/:post_id' }, function() {
this.route('edit');
this.resource('comments', function() {
this.route('new');
});
});
});
CommentsRoute可以获取其所包含资源的模型,然后使用该帖子ID获取评论:
App.CommentsRoute = Ember.Route.extend({
model: function() {
var post = this.modelFor('posts');
var postId = post.get('id');
return App.Comments.find({ id: postId });
}
});
posts模型不需要知道注释id,但基础数据存储区必须根据post id查询返回适当的注释。然后将返回的数组用作注释路径的模型。
修改强>
我假设你正在使用余烬数据。如果是,则尚不支持嵌套资源URL(posts /:postId / comments)。要在发布路径中显示注释,您可能需要获取注释数据,在注释控制器上设置它,在posts控制器中使用控制器注入('needs'),并使用实验'control'手柄标记来显示注释视图:
App.PostsRoute = Ember.Route.extend({
setupControllers: function() {
var post = this.modelFor('posts');
var postId = post.get('id');
var comments = App.Comments.find({ id: postId });
this.controllerFor('comments').set('content', comments);
}
});
我在这里解释如何使用实验控制标签:How to Render HasMany Associations With Their Own Controller