How to get belongsTo object


How do you interact with a model’s belongsTo relationships?

If I have a model:


export default DS.Model.extend({
  referenced_thing: DS.belongsTo('thing'),
  referenced_thing_async: DS.belongsTo('thing_async', {async: true})

Then in a route or a controller, how do I do:

let referenced_thing =

let referenced_thingAsync = 


First in your example referenced_thing and referenced_thing_async are both async. By default ember-data makes all relationships async.

When a relationship is async the value it offers is a proxy to the actual result. You would have to explicitly set { async: false } to remove the proxy involved. However, this assumes that you have side loaded ember-data with the real information in some way (perhaps via JSON:API includes).

The proxy offers the following properties and methods since it is an implementation of Ember’s PromiseProxyMixin:

Specifically if you plan on using the referenced thing in JavaScript land you might do this–

// Modern Ember
let referenced_thing
  = await this.get('modelWithReferences.referenced_thing');
// ember-concurrency
let referenced_thing
  = yield this.get('modelWithReferences.referenced_thing');
// Older Vanilla Ember
  .then(referenced_thing => {
    // referenced_thing is available in here

In templates you can use the derived state–

{{#let modelWithReferences.referenced_thing as |thing|}}
  {{#if thing.isPending}}
    Loading thing…
  {{else if thing.isRejected}}
    Error: {{thing.reason}}