a7omiton
a7omiton

Reputation: 1617

Can't load relationship using "get" Ember 3.2

I'm trying to load a relationship I know hasn't been loaded before, but it seems that it's never calling my API for it.

My setup is:

// routes/application.js
export default Route.extend({
    model() {
        return this.get('store').findRecord('post', 1, {include: 'user'});
    }
});

// routes/comments.js
export default Route.extend({
    model() {
        let post = this.modelFor('application');
        return post.get('user').get('actionHistory');
    }
});

The users actionHistory hasn't loaded before, so I would expect a server request to fetch it, but that's never made. user is available.

// models/user.js
export default DS.Model.extend({
    actionHistory: DS.hasMany('action-history'),
    ...
});

// models/action-history.js
export default DS.Model.extend({
    user: DS.belongsTo('user'),
    ...
});

I've tried many ways to make sure it's loaded, post.load('user.actionHistory'), post.get('user').reload({ include: 'action-history'}), but nothing works.

Is there something wrong with my setup, or the way that I'm trying to fetch the relationship?

Upvotes: 0

Views: 199

Answers (1)

James Byrne
James Byrne

Reputation: 310

As Gaurav mentioned in a comment ember-datas findRecord function will return a promise that needs to resolve first. After it has resolved you should be able to get the user then. For example, the following will return a promise as your model that will resolve to a users action history.

// routes/comments.js
export default Route.extend({
    model() {
        return this.modelFor('application').then(p => p.get('user.actionHistory'));
    }
});

Note that your comments controller/template will not receive a promise from your model hook as ember will wait for it to resolve first.

Upvotes: 1

Related Questions