【问题标题】:How can I update a DS.Model with response json from store.commit()?如何使用来自 store.commit() 的响应 json 更新 DS.Model?
【发布时间】:2012-07-16 22:50:46
【问题描述】:

给定模型:

Blog.Post = DS.Model.extend({
    title: DS.attr('string'),
    tags:  DS.hasMany('Blog.Tag', { embedded: true })
});

Blog.Tag = DS.Model.extend({
    foo: DS.attr('string'),
    bar: DS.attr('string')
});

还有实例:

var myPost = Blog.Post.createRecord({ id: 45, title: 'Foo Bar' })

当我执行 myPost.store.commit()(通过 ember-data 的 DS.RESTAdapter)时,我的服务器会返回一个自动生成的标签列表,这些标签应该应用于 myPost。响应 json 示例:

{
  posts: [
    {
      id: 45,
      title: 'Foo Bar',
      tags: [
        { id: 1, foo: 'bar1' },
        { id: 2, foo: 'bar2' }
      ]
    }
  ]
}

我希望myPost 最终会得到 json 返回的两个标签,但我得到了这个错误:

Error: <DS.StateManager:ember448> could not respond to event invokeLifecycleCallbacks in state rootState.loaded.updated.uncommitted.

我在这里做错了什么?

编辑:澄清 json 以根据@MikeAski 的评论包含 id。给出的示例是我实际案例的简化版本——实际案例确实包含标签 ID。

【问题讨论】:

  • 您是否尝试过加载标签而不是嵌入标签?
  • 有些奇怪:您的标签没有 ID。看起来不对...服务器上的 Tag 模型缺少任何序列化程序吗?
  • @MikeAski 我没有尝试侧载标签——我会试一试并发布结果。更新了问题以包含标签 ID;在将问题简化为一个简单的案例时,我将它们排除在外。
  • 您使用的是什么版本的 ember-data?尝试将您的“myPost”添加到事务并提交事务。

标签: ember.js ember-data


【解决方案1】:

首先你需要“镜像”模型之间的关系:

   Blog.Post = DS.Model.extend({
        title: DS.attr('string'),
        tags:  DS.hasMany('Blog.Tag', { embedded: always })
    });

    Blog.Tag = DS.Model.extend({
        foo: DS.attr('string'),
        bar: DS.attr('string'),
        post: DS.belongsTo('Blog.Post')
    });

然后您需要将映射添加到您的适配器:

Blog.RESTSerializer = DS.RESTSerializer.extend({
  init: function() {
    this._super();

    this.map('Blog.Post',{
      tag:{embedded:'always'},
    });
  }
});

并将 post_id 添加到 JSON 中的 Tag 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    相关资源
    最近更新 更多