0
votes

I have a user JSON api:

{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    }
}

and a post JSON api:

{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  }

I have also created related models in Ember Data: app/models/user.js:

export default Model.extend({
  name: attr('string'),
  username: attr('string'),
  email: attr('string'),
  posts: hasMany('post', { async: true })
});

app/models/post.js:

export default Model.extend({
  title: attr('string'),
  body: attr('string'),
  userId: belongsTo('user')
});

My issue is, I can't access a user's posts from the user object in ember, i.e.: user.posts is empty.

What is the best way to handle this? Does Ember Data require relationships to be embedded in JSON? Or, can I call the posts separately from the store from a Component (I have a component to display all of a user's posts)?

1

1 Answers

0
votes

Ember data does not require it to be embedded, as long as you set the async to true, like you did, you should be able to do either access the posts in a template like so:

// template.hbs
{{#each user.posts as |post|}}
  {{post.title}}
{{/each}}

or in somewhere else in ember with javascript, like so:

this.get('store')
.findRecord('user',1)
.then((user)=> {
    return user.get('posts')
})
.then((posts)=> {
    console.log(posts)
    //use posts here
})