Shimu
Shimu

Reputation: 1147

Ember Data async usage of hasMany

I have nested route with a hasMany relationship. I have declared the model this way:

export default DS.Model.extend({
    label: DS.attr('string'),
    archetyp: DS.attr('number'),
    searchable: DS.attr('boolean'),
    showInList: DS.attr('boolean'),
    managedItem: DS.belongsTo('managedItem')
});

And the corresponding model looks like so:

export default DS.Model.extend({
  title: DS.attr('string'),
  description: DS.attr('string'),
  logo: DS.attr('string'),
  logo_alt: DS.attr('string'),
  fields: DS.hasMany('field', {async: true})
});

And in the fields/index route I want to load the fields from the server. Therefore I have hooked into the model hook.

export default Ember.Route.extend({
  model() {
    let fields = this.modelFor('managedItems/edit').get('fields');
    if (fields.get('isFulfilled')) {
      fields.reload();
    }
    return fields;
  }
});

But I can't see any network request and if I try to console.log(field) I see that the model is empty. What do I miss here?

EDIT: As an additional information: if I just call this.modelFor("managedItems/edit") and ask for some properties of the model object, I always get undefined except for the isLoaded property...
Here is the Router:

Router.map(function() {
  this.route('managedItems', {
  }, function() {
    this.route('new');
    this.route('show', {path: ':managedItem_id'});
    this.route('edit', {path: ':managedItem_id/edit' },
      function() {
           this.route('fields', { resetNamespace: true }, function () {
         });
      });
    });
});

Upvotes: 2

Views: 728

Answers (2)

ykaragol
ykaragol

Reputation: 6221

Change managedItems/edit to managedItems.edit as below:

let fields = this.modelFor('managedItems.edit').get('fields');

"managedItems/edit" is the path of the route (if you don't overwrite it). The name of the route is "managedItems.edit".

Also, fields.reload(); is returning a promise. I'm not sure but IMO the correct model hook function will be like that:

export default Ember.Route.extend({
  model() {
    let fields = this.modelFor('managedItems.edit').get('fields');
    if (fields.get('isFulfilled')) {
      return fields.reload(); //You should return this promise.
    }
    return fields;
  }
});

Upvotes: 0

Nazim
Nazim

Reputation: 367

Your model hook in the route should return a Promise in any case. Have you tried something like:

export default Ember.Route.extend({
    model() {
        return this.modelFor('managedItems/edit').get('fields');
    }
});

Upvotes: 0

Related Questions