Emberjs - unable to request inline model or association

My question displays a small part of this script: http://jsfiddle.net/v2t67/ , but my problem is that I cannot request the json of the child model, i.e. the comment model. At the moment, I can access the parent object (Post Model) from the Chrome chrome 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 inline comments, as shown in this screenshot: http://imgur.com/3WL4I .

So, how will it request a comment using objectAt (0) .toJSON () to return it directly if you need to click the parent inorder object to see it?

Thank you very much.

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
source share
1 answer
  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 } ) }); 

Full code: ** http://jsfiddle.net/v2t67/ **

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

Still adhering to the two models above in our example, we can request the json data of the built-in model (comment model) by doing:

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

When doing further checks, I found that the above will not work if you want to use the json of the parent model (Post model). Here is how I find json for this:

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

You get TypeError: Object does not have a method of 'objectAt' if you try to get json data for Post Model using approach 1, and you get TypeError: you can not call the method 'objectAt' from undefined if you try to get json data for embedded model using approach 2.

I will update this if I learn something new.

  **UPDATE** 

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

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

Source: https://habr.com/ru/post/1434385/


All Articles