15

I have some related models in my ember.js app (using Ember 1.0 and EmberData 1.0 RC2):

App.List = DS.Model.extend({
    listName : DS.attr( ),
    cards : DS.hasMany( 'card', { async : true } )
});

and

App.Card  = DS.Model.extend({
    description : DS.attr(  ),
    list : DS.belongsTo( 'list' )
});

I'm using the following code to save models and add them to a hasMany relationship.

createCard : function(){
    var list = this.get( 'model' ),
        card ;

    card = this.store.createRecord( 'card', {
        description : this.get( 'cardDescription' ),
        list : list
    } );

    card.save().then( function(){
        var cards = list.get( 'cards' );

        cards.then( function(){
            cards.pushObject( card );
            list.save();
        } );
    } );

    this.set( 'cardDescription', '' );
}

I'm running into intermittent issues when saving the parent of the hasMany collection. Sometimes the cards get added to the lists collection properly ( the lists has an array of card id's) and sometimes the cards get added incorrectly ( the lists has an array of card objects) and sometimes the relationship gets lost all together (the lists contains no array of cards).

These symptoms lead me to think that its an async issue or that i'm using the promises incorrectly when saving the objects.

bittersweetryan
  • 3,383
  • 5
  • 28
  • 42

2 Answers2

3

This looks pretty much the same as I have used here. The only difference I can see is that I pushed the child model to the parent in one step (which I doubt makes a difference) and also had the comment (which I guess is the card in your case) as the subject of the promise inside the 'then' function, maybe that makes a difference?

var post = this.get('controllers.post.content');
var comment = this.get('store').createRecord('comment', { post: post, text: this.get('text') });
comment.save().then(function(comment){
  post.get('comments').pushObject(comment);
});
Ian
  • 196
  • 8
2

For current latest EmberData 1.0.0-beta.4+canary.3993001d, I did this only on create in the created mode's didCreate hook for each relation it was bound to. Works so far...

App.Book = DS.Model.extend({
  ...
  didCreate: function() {
    var self = this;
    Em.RSVP.resolve(this.get('author')).then(function(author){
      author.get('books').pushObject(self);
    });
    Em.RSVP.resolve(this.get('category')).then(function(category){
      category.get('books').pushObject(self);
    });
  },
  ...
});
genkilabs
  • 2,966
  • 30
  • 36
  • Yes, we are considering investigating EPF http://epf.io as an alternative to ember data. This may allow for more natural data synching and relations. – genkilabs Aug 11 '14 at 23:42