如何在Ember数据中使用一对多关系(hasMany和belongssto)?

时间:2014-07-16 11:14:13

标签: ember.js ember-data

我是Ember.js的新手,我正在尝试写一个小页面,我们可以发布一些小的状态,人们可以为它添加各种评论。模型定义如下以及数据

Posts.Post= DS.Model.extend({
  title: DS.attr('string'),
  user: DS.attr('string', {defaultValue: 'post user'}),
  comments: DS.hasMany('comment', {async: true})
});
Posts.Post.FIXTURES = [
 {
   id: 1,
   title: 'Learn Ember.js',
   user: 'Post User 1',
   comments: [1,2]
 } 
];

Posts.Comment= DS.Model.extend({
  title: DS.attr('string'),
  user: DS.attr('string', {defaultValue: 'comment user'}),
  post: DS.belongsTo('post')
});
Posts.Comment.FIXTURES = [
 {
   id: 1,
   post_id: 1,
   title: 'Learn Ember.js',
   user: 'Comment User 1'

 },
 {
   id: 2,
   post_id: 1,
   title: 'Post Item 2',
   user: 'Comment User 2'

 },
];

我不确定路由和控制器,我需要能够根据用户的更新更新评论和帖子。

感谢任何帮助。

提前致谢。

1 个答案:

答案 0 :(得分:0)

postpost_id之间存在不匹配。以下内容适用:

你的帖子模型:

Posts.Post= DS.Model.extend({
  title: DS.attr('string'),
  user: DS.attr('string', { defaultValue: 'post user' }),
  comments: DS.hasMany('comment', { async: true })
});

Posts.Post.reopenClass({
  FIXTURES = [
    {
      id: 1,
      title: 'Learn Ember.js',
      user: 'Post User 1',
      comments: [1,2]
    } 
  ],
});

您的评论模型:

Posts.Comment = DS.Model.extend({
  title: DS.attr('string'),
  user: DS.attr('string', { defaultValue: 'comment user' }),
  post: DS.belongsTo('post')
});

Posts.Comment.reopenClass({
  FIXTURES = [
    {
      id: 1,
      post: 1,
      title: 'Learn Ember.js',
      user: 'Comment User 1'
    },
    {
      id: 2,
      post: 1,
      title: 'Post Item 2',
      user: 'Comment User 2'
    },
  ],
});