1
votes

I've got two async models:

App.Posts = DS.Model.extend({
    'content': attr('string'),
    'comments': DS.hasMany('comments', {async: true}),
});

App.Comments = DS.Model.extend({
    'body': DS.attr('string'),
    'postId': DS.belongsTo('posts', {async: true})
});

Via the PostController I try to load the Comments onClick through an action:

App.PostController = Ember.ArrayController.extend({
    loadComments: function(post_id) {
        this.store.find('comments', post_id);
    }
});

(perhaps there is a better way to do this??)

Request and API Response are correct (see API Response below), but only one comment is rendered, then Ember throws an error:

TypeError: Cannot read property 'postId' of undefined

In Embers Console > Data Tab there is one comment in the comment Model, but there is also a post element in the comment model with the comment properties set to undefined. This would explain, why Ember can't read the property postId, because it's not a comment. Why does Ember push the post into the comment model and only pushes one instead of 3 comments into the model?

API Response

{
    "comments": [
        {
            "id": 2,
            "postId": 31152,
            "body": "Lorem ipsum dolor sit amet, consetetur",
        },
        {
            "id": 2,
            "postId": 31152,
            "body": "asdasd",
        },
        {
            "id": 2,
            "postId": 31152,
            "body": "asd asd sd",
        }
    ]
}
1
can you show your router. If your comments are nested in post resource you must specified that in your controller.Stakoov

1 Answers

0
votes

This is a slight shot in the dark, and I'd generally put it as a comment, but it's a tad big. Can you try changing all of the model references to singular. That's the correct pattern for Ember Data models.

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

App.Comment = DS.Model.extend({
    'body': DS.attr('string'),
    'postId': DS.belongsTo('post', {async: true})
});

this.store.find('comment', post_id);

And now that I write this, I might see another issue. If you are querying for comments by post_id (pretend it's 7) then Ember Data is expecting a single record back, not a collection of records. So it's likely looking at the comments collection and thinking it's a single record, and that just blows up it's logic.