Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pushObject to parent in has many relationshop

When trying to push a newly created object to a parent in a has many relationship, I run in an error:

Assertion failed: The content property of DS.PromiseArray should be set before modifying it

Here is my code.

    App.User = DS.Model.extend({
        name : DS.attr('string'),
        selections : DS.hasMany('selection', {async: true}),
        creationDate : DS.attr('date')
    });

    App.Selection = DS.Model.extend({
        value : DS.attr('string')
    });

    App.PollController = Ember.ObjectController.extend({
        actions: {
            save: function(){
                // create new user record in store
                var newUser = this.store.createRecord('user', {
                    name : this.get('newUserName'),
                    creationDate : new Date()
                });

                // create new selection record in store
                var newSelection = this.store.createRecord('selection', {
                    id : 11,
                    value : "hallo"
                });

                // push selection to user
                newUser.get('selections').pushObject(newSelection);

                // save new user
                newUser.save();
            }
        }
    });

Error accourse when I am trying to push the newSelection object to selections Array of user model.

Also tried to change the line to

                // push selection to user
                newUser.get('selections').then(function(selections){
                    selections.pushObject(newSelection);
                });

Then I do not get an error but newSelection is not pushed to user. Selections array of user stays empty.

What I am doing wrong? Am I on totally wrong way? Or is there a bug in EmberJs / Ember Data?

I am using EmberJS 1.2.0 and Ember Data beta 5.

like image 405
jelhan Avatar asked Jan 06 '14 23:01

jelhan


1 Answers

I assume you're saying the save isn't sending back the selections, cause your code for adding is correct.

It's important to note that promises happen asynchronously

            newUser.get('selections').then(function(selections){
                // this will happen after save
                selections.pushObject(newSelection);
            });

            newUser.save();

You should wait to save until the selection is pushed

http://emberjs.jsbin.com/gotasa/1/edit?html,js,output

            newUser.get('selections').then(function(selections){
                selections.pushObject(newSelection);
                newUser.save();
            });
like image 175
Kingpin2k Avatar answered Oct 16 '22 16:10

Kingpin2k