Search code examples
javascriptember.jspromiseember-data

Ember JS 3.1 Why are the ids not loaded with the hasMany relationship?


Here's my version.

$ ember -v 
ember-cli: 3.1.4
node: 8.10.0
os: linux x64

I am trying to do a search using the ids from a has many relationship. There is a Promise, but I can't figure out where to wait for it.

const user = this.get('user');
return user.get('accounts').then((accounts) => {
    console.log(accounts); // Class {canonicalState: Array(0), store: Class, relationship: ManyRelationship, type: ƒ, record: InternalModel, …}
    console.log(accounts.isLoaded); // true
    console.log(accounts.length); // 0
    const ids = accounts.mapBy('id');
    console.log(ids); // <-- Why is this empty?
    return this.store.query('order', { filter: { accounts: ids } });
}

This also doesn't work as expected.

const user = this.get('user');
const accountsRef = user.hasMany('accounts'); // HasManyReference {store: Class, internalModel: InternalModel, hasManyRelationship: ManyRelationship, type: "account", parent: RecordReference}
const ids = accountsRef.ids(); // []

And this fails in the same way.

const user = this.get('user');
const promise = new RSVP.Promise((resolve, reject) => {
    return user.get('accounts').then((accounts) => {
        resolve(accounts);
    });

return promise.then((data) => {
    console.log(data); // // Class {canonicalState: Array(0), store: Class, relationship: ManyRelationship, type: ƒ, record: InternalModel, …}
    const ids = accounts.mapBy('id');
    console.log(ids); // []
});

The has many relationship on User is defined as accounts: DS.hasMany('account') and the deserializer uses records.

This works in the Handlebar template, and produces the list of IDs I am interested in.

{{#each user.accounts as |account|}}
  {{account.id}} - {{account.name}}
{{/each}}

What is happening between the model hook and the template rendering? Where else do I need to look to troubleshoot?


Solution

  • The problem was not Ember or Ember Data. My API was not responding with embedded records OR the association's id. Check that your API matches the specification.