Search code examples
ember.jsember-data

Accessing relationship field in emberjs template?


Here is the current structure that i have on my emberjs model

import DS from 'ember-data';

export default DS.Model.extend({
  team: DS.belongsTo('team'),
  opponent: DS.belongsTo('team'),
  type: DS.attr('string'),
});

and the template that i am calling it from is as follows

  <div class="container">
    {{#each model as |match|}}
      <div class="match">
        <code>Match type : {{match.type}}</code>
        <p>Team 1 : {{match.team.name}}</p>
      </div>
    {{/each}}
  </div>

Now the match.team returns me a promise. My question is how do i render the name on template side.

The team with proper id was already populates with model api call as relationship.

EDIT

The problem is that the Promise resolved to no content. The following is the json response

{
  "meta": {
    "type": "match"
  },
  "included": [{
    "type": "team",
    "id": 3,
    "attributes": {
      "id": 3,
      "name": "teamName",
      "logo": null,
      "created-at": "2018-06-05T07:05:42.000Z",
      "updated-at": "2018-06-05T07:05:42.000Z"
    }
  }],
  "data": [{
    "id": 1124639,
    "type": "match",
    "attributes": {
      "id": 1124639,
      "team": 77,
      "opponent": 1,
      "starts-on": "2018-06-10T00:00:00.000Z",
      "created-at": "2018-06-05T08:30:13.000Z",
      "updated-at": "2018-06-05T08:30:13.000Z",
      "relationships": {
        "team": {
          "data": {
            "id": 77,
            "name": "teamName",
            "logo": null,
            "created-at": "2018-06-05T07:05:57.000Z",
            "updated-at": "2018-06-05T07:05:57.000Z",
            "type": "team"
          }
        }
      }
    }
  }]
}

I am assuming something is wrong with the structure for relationships but can't get my finger on what exactly ?


Solution

  • The resonse shown isn't standard JSON-API. You wan't something that looks like this:

    {
      "meta": {
        "type": "match"
      },
      "included": [{
        "type": "team",
        "id": 77,
        "attributes": {
          "id": 77,
          "name": "teamName",
          "logo": null,
          "created-at": "2018-06-05T07:05:42.000Z",
          "updated-at": "2018-06-05T07:05:42.000Z"
        }
      }],
      "data": [{
        "id": 1124639,
        "type": "match",
        "attributes": {
          "id": 1124639,
          "opponent": 1,
          "starts-on": "2018-06-10T00:00:00.000Z",
          "created-at": "2018-06-05T08:30:13.000Z",
          "updated-at": "2018-06-05T08:30:13.000Z"
        },
        "relationships": {
          "team": {
            "data": {
              "id": 77,
              "type": "team"
            }
          }
        }
      }]
    }