【问题标题】:How can I create a record with a nested/embedded record in Ember Data?如何在 Ember Data 中创建具有嵌套/嵌入记录的记录?
【发布时间】:2015-07-21 18:16:40
【问题描述】:

使用 Ember Data 创建记录时如何创建嵌套/嵌入模型?具体来说,我想创建一个带有嵌套/嵌入式模型作者的帖子模型。以下代码给了我错误:

处理路由时出错:索引断言失败:您无法将“未定义”记录添加到“post.author”。您只能向此关系添加“作者”记录。错误:断言失败:您无法将“未定义”记录添加到“post.author”。您只能向此关系添加“作者”记录。

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.createRecord('post', {
      title: 'My first post',
      body: 'lorem ipsum ...',
      author: {
        fullname: 'John Doe',
        dob: '12/25/1999'
      }
    });
  }
});

App.Post = DS.Model.extend({
  title: DS.attr('string'),
  body: DS.attr('string'),
  author: DS.belongsTo('author')
});

App.Author = DS.Model.extend({
  fullname: DS.attr('string'),
  dob: DS.attr('string')
});

关于如何做到这一点的任何想法?我还在 JSBin 上创建了一个演示:http://emberjs.jsbin.com/depiyugixo/edit?html,js,console,output

谢谢!

【问题讨论】:

    标签: ember.js ember-data


    【解决方案1】:

    需要将关系分配给实例化模型,普通对象不起作用。

    App.IndexRoute = Ember.Route.extend({
      model: function() {
        return this.store.createRecord('post', {
          title: 'My first post',
          body: 'lorem ipsum ...',
          author: this.store.createRecord('author', {
            fullname: 'John Doe',
            dob: '12/25/1999'
          })
        });
      }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多