Ricky Mason
Ricky Mason

Reputation: 1828

Displaying parent attributes in child view in Ember

I have the following view:

templates/posts/index.hbs

{{#each}}
  {{~#link-to 'posts.show' this}}
    {{title}}({{category.name}})<br>
  {{~/link-to}}
{{/each}}

Post belongs to Category, which has a has_many relationship with Post.

However, {{category.name}} currently is empty. The data tab in Chromes ember inspector for Category in general is empty.

My json looks like this :

{
posts: [
{
  id: 1,
  title: "What's up with Docs?",
  category: 1
},
{
  id: 2,
  title: "Of course, you know, this means war.",
  category: 1
}]
}

I am currently on the app.com\posts index page, which means I am pulling in just that JSON.

According to the ember docs (http://emberjs.com/guides/models/the-rest-adapter/#toc_relationships) it looks as if my json is formatted correctly. However I am clearly having an issue pulling in the category attributes.

Here are my ember models:

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    posts: DS.hasMany('post')
});

export default DS.Model.extend({
    title: DS.attr('string'),
    category: DS.belongsTo('category')
});

Any help would be great. Again .. im just trying to display the child's(post) parents(category) name on the post view.

Thanks

Upvotes: 1

Views: 64

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

category: DS.belongsTo('category') either needs to be defined as async category: DS.belongsTo('category', {async:true}) or you need to include the category in the reponse.

{
  posts: [
  {
    id: 1,
    title: "What's up with Docs?",
    category: 1
  },
  {
    id: 2,
    title: "Of course, you know, this means war.",
    category: 1
  }],
  categories: [
  {
    id: 1,
    ...
  }
  ....
]
}

Upvotes: 0

Related Questions