alvincrespo
alvincrespo

Reputation: 9334

Accessing nested hasMany relationship in Ember / Ember Data

I'm trying to access a nested hasMany relationship, expecting the promise. Unfortunately I do not get the expected results with any of the following:

// Tried the following
this.get('users.emails')
this.get('[email protected]')
this.get('users').get('emails')

// Trying to avoid this:
this.get('users').
  then(function(users) {
    var arr = Ember.A();

    users.forEach(function(user, index){
      arr.pushObject(user.get('emails'));
    });

    return array;
  }).
  then(function(emailArr){
    // then do something
  });

// Preferable
this.get('users.emails').then(function(emails){
  // then do something
});

Upvotes: 3

Views: 594

Answers (1)

blaineh
blaineh

Reputation: 2333

If you've defined your model with the async value set to true like this:

users: DS.hasMany('user', {async: true})

then typically calling this.get('users') will return a promise array, and might not be resolved by the time you actually start using it.

Nested gets are tricky, especially with the complication of asynchronous models, so I recommend you do this:

this.get('users').then(function(users) {
    users.get('emails').then(function(emails) {
        // do stuff with emails.
    });
}

Annoying? Absolutely. Probably necessary? Yeah.

Upvotes: 4

Related Questions