ember.jsember-datarsvp-promise

Ember isn't always loading belongsTo


I can't seem to workout how to load relationships properly in Ember. The user model only returns some of the time. If I refresh the page there seems to be a 50/50 chance the value will be null, or it will resolve correctly.

I understand in the route I'm returning a promise which is the server object (the belongsTo end of the user relationship), but how do I tell the route to wait for the user model to load before loading the page, or how do I tell ember to update the data on the page when it finally does load the user?

I've tried playing around with RSVP in the afterModel hook but haven't had any luck. There must be a obvious solution to this?

route

model(param) {
  return this.store.findRecord('server', param.server_id);
},

server model

export default Model.extend(Validations, {
  user: belongsTo('user'),
});

user model

export default Model.extend({   
  displayName: attr('string'),
  servers: hasMany('server'),
});

component

export default Ember.Component.extend({});

component template

<div class="user-panel">
    <ul class="user-details">
        <li>owner:{{model.user.displayName}}</li>
    </ul>
</div>

I've read a similar question here How to load belongsTo/hasMany relationships in route with EmberJS

But as I'm only returning a single object rather than an array I get Array Methods must be provided an Array thrown when trying any of the solutions

Server response

{
  "data": {
    "type": "server",
    "id": "578aba694b08ce2310f36798",
    "attributes": {
      //removed
    },
    "relationships": {
      "jobs": {
        "data": [
          {
            "type": "jobs",
            "id": "578aba694b08ce2310f3679a"
          }
        ]
      },
      "user": {
        "data": {
          "type": "user",
          "id": "57760677d04e0f11f4d3f7e5"
        }
      }
    }
  }
}

Solution

  • This should work out of the box! Not the waiting part, but the auto update.

    Checkout this twiddle.

    But if you want to wait for the model you can just enforce this in the afterModel hook:

    afterModel(model) {
      return get(model, 'user');
    }