【问题标题】:What is the correct way to persist child model with Ember.js?使用 Ember.js 持久化子模型的正确方法是什么?
【发布时间】:2013-09-18 12:25:57
【问题描述】:

问题

我正在自学 Ember,但在坚持我的子模型时遇到了问题。这是一个演示问题的 JSBin:

http://jsbin.com/OnUXEti/2/edit?html,js,output

如果您使用它,您将能够创建帖子和评论,但只有帖子在页面重新加载后仍然可用。 (我正在使用 ember-data 和 localStorage 适配器)


有两种模型类型,PostComment

App.Post = DS.Model.extend({
  title: DS.attr('string'),
  comments: DS.hasMany('comment')
});

App.Comment = DS.Model.extend({
  message: DS.attr('string')
});

每个帖子都有一组评论。 我打算有以下网址:

  • /posts 将列出所有帖子
  • /posts/1 将显示 id 为 1 的帖子
  • /posts/1/comments 将显示帖子 1 的评论

路由是这样定义的:

App.Router.map(function() {
  this.resource("posts", { path: "/posts" });
  this.resource("post", { path: "/posts/:post_id" }, function() {
    this.resource("comments", { path: "/comments" });
  });
});

我可以毫无问题地将 Post 模型写入商店。我不能做的是保存评论模型。如果您使用我上面的 JSBin 示例,您将看到您可以创建 cmets,但在重新加载页面时它们不会持久化。

我尝试在 CommentsController 中保存评论:

App.CommentsController = Ember.ArrayController.extend({
    needs: "post",
    post: Ember.computed.alias("controllers.post"),
    newMessage: '',
    actions: {
        create: function() {
            var message = this.get('newMessage');

            var comment = this.store.createRecord('comment', {
                message : message
            });

            this.set('newMessage', '');

            var post = this.get('post');
            var comments = post.get('comments');
            comments.pushObject(comment);
            comment.save();
        }
    }
});

请注意,我通过使用 needs 属性获得了父 Post 的句柄。取自documentation about dependencies between controllers

这一切都感觉不对,因为它应该是一种常见的情况,所以我怀疑我以非标准方式设计了我的模型或路线。

谢谢, 马特

【问题讨论】:

  • 我看到了问题,我正在尝试您的小提琴...您的模型似乎正在更新,但您的帖子模型似乎没有得到反映...映射到您的评论对象...

标签: ember.js ember-data


【解决方案1】:

这里的问题是您需要在将comment 添加到其comments 集合后保存post。看起来 LSAdapter 将评论 ID 数组直接存储在 post 记录中。

这是一个修改后的 JSBin:http://jsbin.com/OnUXEti/8/edit

注意:我也改变了这个:

post: Ember.computed.alias("controllers.post")

到这里:

post: Ember.computed.alias("controllers.post.model")

为了保存post,您要处理实际模型,而不是控制器。

我还必须更新 Ember Data 和 LSAdapter 才能正常工作,我将 comments 上的 hasMany 关系更改为 async

comments: DS.hasMany('comment',{async:true})

[更新]:我最初发布了错误的 JSBin。正确的是:http://jsbin.com/OnUXEti/8/edit

【讨论】:

  • +1 : 哇,我确实对帖子属性进行了更改,但没有更改关系....太棒了...
  • 非常感谢您抽出宝贵时间!你是学者,也是圣人!多亏了你,我意识到我有两个问题:1)我没有保存“post”模型。 2) 我需要使用 ember-data-latest.js。我创建了另一个 JSBin,它只进行了使其工作所需的最小更改。请注意,我不需要更新 LSAdapter,也不需要在我的帖子模型上设置“异步”选项。 jsbin.com/OnUXEti/17/edit?html,js,output 如果我能给你更多的分数,我正准备放弃 ember,就像我开始喜欢它一样:) 再次感谢,Matt。
  • 啊,我需要异步选项,否则有时我会收到错误消息:“未捕获的类型错误:无法读取未定义的属性'resolve'”。再次感谢!
  • 对我来说,我需要异步并且我没有为我的适配器定义序列化程序:App.ApplicationSerializer = DS.LSSerializer.extend();
猜你喜欢
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多