我有两个异步模型:

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})
});


通过PostController,我尝试通过一个动作加载Comment onClick:

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


(也许有更好的方法可以做到这一点?)

请求和API响应是正确的(请参阅下面的API响应),但是仅呈现一个注释,然后Ember引发错误:

TypeError: Cannot read property 'postId' of undefined


在Embers Console>“数据”选项卡中,注释模型中有一个注释,但注释模型中还有一个post元素,其注释属性设置为undefined。这可以解释为什么Ember无法读取属性postId,因为它不是注释。 Ember为什么将帖子推送到评论模型中,而只将一个而不是3条评论推送到模型中?

API响应

{
    "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",
        }
    ]
}

最佳答案

这是在黑暗中的轻微镜头,我通常将其作为评论,但这有点大。您可以尝试将所有模型引用更改为单数吗?这是Ember Data模型的正确模式。

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);


现在,我写了这篇文章,我可能会看到另一个问题。如果您要通过post_id(假设它是7)来查询评论,那么Ember Data期望返回一条记录,而不是记录的集合。因此,很可能查看评论集合并认为它是单个记录,这只会炸毁它的逻辑。

10-05 21:06
查看更多