Search code examples
javascriptember.jsember-model

access to a related collection in an ember-model object via hasMany relationship


I may fundamentally be misunderstanding how to use the hasMany relationships in Ember/ember-model.

the ember-model readme has the following example

postJson = {
  id: 99,
  title: 'Post Title',
  body: 'Post Body',
  comments: [
    {
      id: 1,
      body: 'comment body one',
    },
    {
      id: 2,
      body: 'comment body two'
    }
  ]
};

App.Post = Ember.Model.extend({
  id: Ember.attr(),
  title: Ember.attr(),
  body: Ember.attr(),
  comments: Ember.hasMany('App.Comment', {key: 'comments', embedded: true})
});

App.Comment = Ember.Model.extend({
  id: Ember.attr(),
  body: Ember.attr()
});

presumably, one would do the following

post = App.Post.create();
post.load(1, postJson);

given the above, now we have access to various post props via get (i.e. post.get('title')), but how to I access the comments?

post.get('comments') returns an object, but it is not a collection of App.Comment objects, which is what I'd expect.

Thanks in advance for any and all help.


Solution

  • It returns a collection object which is iterable, but not an array. I'm working up an example with your code, I'll post it up momentarily (I'm pretty sure load is a private method and you should be using load on the model definition, then find).

    App.Post.load(postJson); //sideloading
    return App.Post.find(99);
    

    http://jsbin.com/hocopoga/1/edit