简体   繁体   中英

Ember.js ember-data render double nested hasMany relationship

I am trying to build a little app using ember data and I am trying to render all songs of an artist through its albums.

My models look like:

App.Artist = DS.Model.extend({
  name: DS.attr('string'),
  albums: DS.hasMany('album', {async:true})
});

App.Song = DS.Model.extend({
  title: DS.attr('string'),
  artist: DS.belongsTo('App.Artist'),
  album: DS.belongsTo('App.Album')
});

App.Album = DS.Model.extend({
  title: DS.attr('string'),
  cover_url: DS.attr('string'),
  artist: DS.belongsTo('artist'),
  songs: DS.hasMany('song', {async:true})
});

And in the template I am trying to render it like:

<script type='text/x-handlebars', data-template-name='artists'>
  {{#each artist in model}} 
    {{#linkTo 'artist' artist}}{{artist.name}}({{artist.albums.length}}){{/linkTo}}
   {{/each}}
   {{outlet}}
</script>

<script type='text/x-handlebars', data-template-name='albums'>
      {{#each album in albums}}
        <h3>{{album.title}}</h3>
        {{#each song in album.songs}}
          {{song.title}}
        {{/each}}
      {{/each}}
</script>

The album title is displayed correctly but the song titles are not shown. Ember sends a request to the server loading the songs for the albums and album.songs is DS.ManyArray:ember461 .

The response looks like:

{
  songs: [
  {
   id: 8
   artist_id: 1,
   album_id: 5,
   title: "title"
  }
 ]
}

What could be the reason for album.songs not beeing resovled?

Thanks for your help.

The problem was that I specified the relationships on Song incorrectly:

App.Song = DS.Model.extend({
  title: DS.attr('string'),
  artist: DS.belongsTo('App.Artist'),
  album: DS.belongsTo('App.Album')
});

becomes:

App.Song = DS.Model.extend({
  title: DS.attr('string'),
  artist: DS.belongsTo('artist'),
  album: DS.belongsTo('album')
});

Unless you have a special serializer, or an older version of Ember Data, your json is wrong.

{
  songs: [
  {
   id: 8
   artist_id: 1,
   album_id: 5,
   title: "title"
  }
 ]
}

should be

{
  songs: [
  {
   id: 8
   artist: 1,
   album: 5,
   title: "title"
  }
 ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM