2
votes

I have a collection of comments and a collection of posts.

App.Router.map(function () {
  this.resource("posts", {
    path: "/posts"
  });
  this.resource("post", {
    path: "/:post_id"
  }, function () {
    this.resource("comments", {
      path: "/comments"
    });
  });
});
App.Post = Ember.Model.extend({
  id: attr(),
  name: attr(),
  comments: Ember.hasMany("App.Comment", {
    key: 'comments'
  })
  if embedded = comments: Ember.hasMany("App.Comment", {
    key: 'comments',
    embedded: true
  })
});
App.Post.url = "/posts";
App.Comment = Ember.Model.extend({
  id: attr(),
  message: attr(),
  post: Ember.belongsTo('App.Post', {
    key: 'post'
  })
});

How can I either:

  1. Create a new embedded comment.
  2. Create a non-embedded comment and have that creation add the comment_id into comment_ids: [] on the Post model.

I can get the post_id to enter into the comments if non-embedded, but am having difficulty getting the comment_id added into the post.

3

3 Answers

1
votes

Use the create() method.

// get a post instance to insert a new comment to.
var post = App.Post.create(); // or App.Post.find()

// insert a new comment.
var comment = post.get('comments').create();
comment.message = "Test Poster";

// since you are using embedded relationship,
// no need to save the comment, just save the post.
post.save();

If you are using non-embedded comment, change your relationship to { embedded: false }, just don't forget to call save on your comment.

// if non-embedded
comment.save();

Hope it helps!

0
votes

You have to push the new comment into the comments collection on the post.

var post = this.get('post');
var comments = post.get('comments');
comments.pushObject(comment);
comment.save();
post.save();

Here's a JSBin with the general idea : http://jsbin.com/OnUXEti/12/edit

0
votes

in case this helps anyone -- i put in pull request on ember-model that fixes issue pull request diff on github