Ember Data- createRecord in a hasMany relationship

天涯浪子 提交于 2019-12-23 01:59:13

问题


I am using Ember Data beta2 and I have a hasMany relationship set up.

When creating a child record do I have to use pushObject on the parent's corresponding property?

When looking at the documentation I get the impression that I need to correctly set the record's parent property and save it.

This is how I do it:

    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();
    }

I see the newly created record in the Ember inspector in Chrome, it is not dirty, but it is not present in the parent listing and after I refresh it is gone.


回答1:


What works for me is the following:

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

I don't know what addPlugin belongs to, but if you are creating the children from a ChildrenArrayController you may want to include

needs: ['parent']

in your controller. And before creating the child and adding it to the parent you will need to call:

var parent = this.get('controllers.parent');


来源:https://stackoverflow.com/questions/18917199/ember-data-createrecord-in-a-hasmany-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!