ShinySides
ShinySides

Reputation: 428

EmberJS simple ID from related object

is there any way to do some filtering based on the related ID? imagine I have 2 models one is a song model and the other is an album model so obviously the song has album with an id, the json will return the model with

{album: 1}

so if I wanna filter it seems that I can't compare the album id with something like

song.get('album.id') === 1

is there any way to do it so simply?

Thanks

Edit: models

App.Album = DS.Model.extend({
   irrelevantstuff: DS.attr(),
   songs: DS.hasMany('Song')
})

App.Song = DS.Model.extend({
   irrelevantstuff: DS.attr(),
   album: DS.belongsTo('Album')
})

I tried both with {async:true} and without, still same problem.

however I noticed that if I run it the first time it gives me undefined to all of the album.id but if I run it the second time I get the ids, now I have everything on the store, so it's not doing an AJAX request either the first or second time.

{"songs": [{"irrelevantstuff":"foo", "album": 1}, {"irrelevantstuff":"bar", "album": 1}]}

{"albums": [{"irrelevantstuff":"album", "songs": [1,2]}]

Upvotes: 0

Views: 31

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

Relationships should be camelCase

App.Album = DS.Model.extend({
   irrelevantstuff: DS.attr(),
   songs: DS.hasMany('song', {async: true})
})

App.Song = DS.Model.extend({
   irrelevantstuff: DS.attr(),
   album: DS.belongsTo('album', {async: true})
})

Since your data for the relationship isn't coming down in the request for the song/album it would be considered async. As such if you want to access it you'll need to use it asynchronous methods, promises.

var songPromise = this.store.find('song', 1);

songPromise.then(function(song){
  var albumPromise = song.get('album');
  albumPromise.then(function(album){
    // the album is available for usage....
    if(album.get('id') == 1){
      alert('woo hoo');
    }
  });
});

Upvotes: 1

Related Questions