我一直在 Google 和 Stack Overflow 上搜索有关这个主题的某种提示,但信息充其量是分散的。
我正在尝试创建一个新的子记录(Comment
)并将其保存到现有的父记录(Post
)。我使用的是 Ember-Model,而不是 Ember-Data,但任何提示或指示将不胜感激。
目前,我已经成功创建了一个新的嵌入式Comment
but only当它被创建时new Post
记录。所以:
我如何加载/检索当前加载的Post
(家长记录)以便申请Comments
(子记)要吗?
我一直在阅读控制器依赖项,使用needs:
and this.controllerFor
and this.modelFor
为了能够访问另一个控制器/模型的content
但无法将这些东西连接成有意义的东西。
不管怎样,这就是我将应用程序代码缩减到的内容,希望我能够偶然发现执行此操作的正确方法......
Routes
App.Router.map(function() {
this.resource('post', { path: '/:post_id' }, function() {
this.resource('comments', { path: '/comments'} );
});
});
我删除了所有其他资源和路线,所以我留下了App.Post
, App.PostIndex
, and App.Comments
。我认为我的路线是这里的问题,我假设我没有正确实现使用加载的方法Post
记录在我的Comments
route.
App.IndexRoute = Ember.Route.extend({
model: function() {
return App.Post.find();
},
setupController: function(controller, model) { // I'm not certain if this
controller.set('content', model); // setupController is needed?
}
});
App.PostRoute = Ember.Route.extend({
model: function(params) {
return App.Post.find(params.post_id);
},
setupcontroller: function( controller, model) { // again, unsure if this
this.controllerFor('post').get('comments'); // is correct.
controller.set('content', comments);
}
});
App.CommentsRoute = Ember.Route.extend({
afterModel: function() {
this.set('post', this.modelFor('post'));
},
setupcontroller: function( controller, model) {
this.controllerFor('post').get('comments');
controller.set('content', comments);
}
});
控制器
App.CommentsController = Ember.ArrayController.extend({
needs: "post",
actions: {
addComment: function() {
var post = App.Post.create({
title: 'static post title'
});
post.get('comments').create({
message: 'static message'
});
post.save();
}
}
});
这是我当前的评论控制器,它可以创建一个新的Post
带有嵌入式Comment
。我发现并得到了许多创建Comment
,但似乎没有一个对我有用。基本上,我正在努力定义var post = ...
作为当前加载的记录。我已经实施了各种方法来尝试试错。到目前为止我已经尝试过:
var post = App.Post.create();
,返回属性未定义,因为这将创建一个新记录。然而,我尝试了一下,因为我看到的每个与此相关的例子都定义了他们的记录。
var post = this.get('post');
,返回无法在未定义时调用“get”。我尝试过使用这种方法来定义我当前的帖子Comments
控制器和Post
控制器。
var post = this.get('controllers.post.content);
,从我正在使用的后端返回“循环错误”。
var post = App.Post.find();
,返回无法在未定义时调用“get”。
var post = App.Post.find(1);
,再次返回一个无法调用“get”的未定义。我想我会尝试一下,因为这是人们提供的反复出现的例子之一。我使用的后端将其自己的 ID 应用于每条记录,我不确定是否能够/如何拥有.find()
方法使用动态 ID 值并仅检索我刚刚加载的模型。
我猜我没有正确设置我的路由和控制器依赖项?
如果有人有建议、相关链接或修复,我将非常感激。
这个(看似简单的)问题/用例让我此时束手无策。