Emberjs - unable to query for embedded model or association

你离开我真会死。 提交于 2019-12-24 08:58:56

问题


A small portion of this fiddle: http://jsfiddle.net/v2t67/ is displayed in my question, but my problem is that i am unable to query for the json of the child model ie the comment model. As of now, i can access the parent object (Post Model) from chrome developer console using the queries below and from the result that contains the parent object, in the console, i can click on it and i will see the embedded comments as shown in this screenshot: http://imgur.com/3WL4I.

So how will query for the comment using objectAt(0).toJSON() to return it directly with out needing to click on the parent Object inorder to see it?

Many thanks.

 yt = App.store.findAll(App.Post)
 yt.objectAt(0).toJSON()   //to display the json for post

App.Comment = DS.Model.extend({
    content: DS.attr('string'),
    post: DS.belongsTo('App.Post')
});


App.Post = DS.Model.extend({
    body: DS.attr('string'),
    comments: DS.hasMany('App.Comment', { embedded: true } )
});

回答1:


 App.Comment = DS.Model.extend({
   content: DS.attr('string'),
   post: DS.belongsTo('App.Post')
 });


 App.Post = DS.Model.extend({
   body: DS.attr('string'),
   comments: DS.hasMany('App.Comment', { embedded: true } )
 });

For the full code see: ** http://jsfiddle.net/v2t67/**

After reading the test for association from the source, i found a way to do it. The test for association is here: ** https://github.com/emberjs/data/blob/master/packages/ember-data/tests/unit/associations_test.js**

Still sticking to the two models above as our example, we can query for the json data of the embedded model (Comment model) by doing:

      **Approach 1**

 query = App.store.find(App.Post,  1)
 query.get('comments').objectAt(0).toJSON()

While doing further checks, i discovered that the above will not work if you want the json of the parent model (Post model). This is how i go the json for that:

      **Approach 2**

 query = App.store.find(App.Post)
 query.objectAt(0).toJSON()

You will get a TypeError: Object has no method 'objectAt', if you try to get the json data for the Post Model using approach 1 and you will get TypeError: Cannot call method 'objectAt' of undefined, if you try to get the json data for the embedded model using approach 2.

I will update this, if i find out something new.

           **UPDATE**

You can get the approach 2 to return the json data for the embedded model without error by passing {associations: true}, to the toJSON() function as shown below:

 query = App.store.find(App.Post)
 query.objectAt(0).toJSON({associations: true})


来源:https://stackoverflow.com/questions/12124799/emberjs-unable-to-query-for-embedded-model-or-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!