简体   繁体   中英

Ember Data- createRecord in a hasMany relationship

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.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM