Ember Data 1.0.0 Beta add Object to hasMany relationship


#1

I want to add an new object to an hasMany relationship. For example I have an ‘post’-model and a post can have many comments. So I have also an ‘comment’-model.

App.Task = DS.Model.extend({
  subject: DS.attr('string'),
  text: DS.attr('string'),
  comments: DS.hasMany('comment', { async: true }),
});

App.Comment = DS.Model.extend({
  text: DS.attr('string'),
  created: DS.attr('number'),
});

What is the best way to add an new comment to an existing post? I created an new comment object an post it to server, after receive the new comment object from server I want to add the comment-object to the post-object. After adding I must save the post-object.

How I can add the comment-object to post-object?

 var post = this.get('model');
 var comment = this.store.createRecord('comment');
 comment.set('text', ' thats some text');
 comment.set('created', '11111212');
 comment.save().then(function(resolvedComment){
   post.get('comments').addObject(resolvedComment);
   post.save();
});

#2

Please first read this: http://stackoverflow.com/questions/18703867/ember-data-save-loses-belongsto-relationship/18739320?noredirect=1#18739320

There is a problem in Ember Data 1.0 Beta 1 and 2 due to which hasMany relationships do not work … However, if you use the latest canary build and modify the code as suggested by Amar @amarpalsapure, then it will work.

Below is the code I use to save a hasMany, but the structure is identical to yours: first save the comment, add the comment to the post and then save the post.

ps. In my code, I also set the publication_id in the comment model, but this is not necessary (depends on how you want to retrieve later on the comments).

save: function () {

  this.set('isAddingNew', false);
  
  //Create a new comment record
  var comment = this.store.createRecord('comment', {
    commenttext: this.get('commenttext'),
    publication: this.get('controllers.publicationsShow.content')
  });
 
  //The publication to be updated
  var publication = this.get('controllers.publicationsShow.content');
  
  //Save the comment and then the publication
  comment.save().then(
    function () {
      //Succesful save of comment; thus add to publication
      publication.get('comments').addObject(comment);
      
      //Save publication
      publication.save().then(
        function () {
          //Succesful save of publication
        },
        function (error) {
          console.log("API error occured - " + error.responseText);
          alert("An error occured - REST API not available - Please try again");
        }
      );
    },
    function (error) {    
      console.log("API Error occured - " + error.responseText);
      alert("An error occured - REST API not available - Please try again");
    }
  );
}

#3

Have sent a pull request https://github.com/emberjs/data/pull/1273


#4

Why haven’t you defined a belongsTo on your comment?