Ember灯具和很多关系

时间:2014-07-19 22:46:43

标签: javascript ember.js

出于某种原因,下面的代码会导致Error while loading route: TypeError: Cannot read property 'typeKey' of undefined。一切都很好,直到我在Note灯具中添加评论。我假设嵌套在注释夹具中的注释会起作用,因为这是API返回它的方式,但这似乎是断点。

**我应该注意到我已经尝试将夹具添加到评论模型中,并使用note_id引用回到笔记。我没有收到错误,但我没有收到任何回复**

感谢您的帮助。

模型/ note.js

import DS from 'ember-data';

var Note = DS.Model.extend({
  content:  DS.attr('string'),
  comments: DS.hasMany('comment'),
});

Note.reopenClass({
  FIXTURES: [
    {
      id: 1,
      content: 'This is the first comment',
      comments: [
        { id: 1, content: 'First comment' },
        { id: 2, content: 'Second comment' },
        { id: 3, content: 'Third comment' }
      ]
    },
    {
      id: 2,
      content: 'This is the second comment',
      comments: [
        { id: 4, content: 'First comment' },
        { id: 5, content: 'Second comment' },
        { id: 6, content: 'Third comment' }
      ]
    }
  ]
});

export default Note;

模板/ notes.hbs

{{#each}}
<div>
  <div>{{content}}</div>

  {{#each comments}}
  {{this.content}}
  {{/each}}
</div>
{{/each}}

模型/ comment.js

import DS from 'ember-data';

var Comment = DS.Model.extend({
  content:   DS.attr('string'),
  timestamp: DS.attr('date'),

  note: DS.belongsTo('note')
});

Comment.reopenClass({
  FIXTURES: [
    { id: 1, content: 'First comment',  note_id: 1 },
    { id: 2, content: 'Second comment', note_id: 1 },
    { id: 3, content: 'Third comment',  note_id: 1 }
  ]
});

export default Comment;

1 个答案:

答案 0 :(得分:1)

看起来我错过了几件事。

在设置为true的关系中需要 async 选项

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

需要在父级中为子级设置关系

Note.reopenClass({
  FIXTURES: [
    {
      id: 1,
      content: 'This is the first comment',
      comments: [1, 2, 3]
    },
    {
      id: 2,
      content: 'This is the second comment',
      comments: [4, 5, 6]
    }
  ]
});