brg
brg

Reputation: 3953

Emberjs - unable to query for embedded model or association

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: https://i.sstatic.net/GkYcb.jpg.

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

Upvotes: 1

Views: 934

Answers (1)

brg
brg

Reputation: 3953

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

Upvotes: 1

Related Questions