Ember Data-以hasMany关系创建记录

rk1*_*rk1 1 javascript ember.js ember-data

我正在使用Ember Data beta2,我设置了hasMany关系.

在创建子记录时,我是否必须在父对应的属性上使用pushObject?

在查看文档时,我得到的印象是我需要正确设置记录的父属性并保存它.

我是这样做的:

    addPlugin: function() {
        //get the value
        var title = this.get('newPluginName');
        if (!title.trim()) { return; }

        var plugin = {
            name: title,
            category: this.get('model'),
            url: ''
        };
        var plugin = this.store.createRecord('plugin', plugin);
        plugin.save();

        //clear the text field
        this.set('newPluginName', '');
        $("#new-plugin").blur();
    }
Run Code Online (Sandbox Code Playgroud)

我在Chrome中的Ember检查器中看到了新创建的记录,它并不脏,但它不存在于父列表中,刷新后它就消失了.

cho*_*per 8

对我有用的是:

var child = this.get('store').createRecord('child', {
   name: 'New Child',
   parent: parent
};
child.save();

parent.get('children').addObject(child);
// My backend automatically adds the inverse of relationships when saving     
// the child, so I don't need to save the parent separately
Run Code Online (Sandbox Code Playgroud)

我不知道addPlugin属于什么,但如果你是从ChildrenArrayController创建孩子,你可能想要包括

needs: ['parent']
Run Code Online (Sandbox Code Playgroud)

在你的控制器中.在创建子项并将其添加到父项之前,您需要调用:

var parent = this.get('controllers.parent');
Run Code Online (Sandbox Code Playgroud)

  • 看起来Ember Data的最新版本在这方面是错误的.我有一个问题,有时(虽然不总是)子元素没有从父母关系中删除.对我有用的是修补它,就像我的回答[这里](http://stackoverflow.com/questions/18806533/deleterecord-does-not-remove-record-from-hasmany)中所述.另请参阅github上的[此相关问题](https://github.com/emberjs/data/issues/1303). (2认同)