ember.jsember-dataember-cliember-components

Ember 2.7 model inheritance - how to access data in the template that comes from a model related to parent?


In Ember 2.7 assume you have a Person class that has an Address model (assume city:DS.attr() is the only attribute).

app/models/person.js

import DS from 'ember-data';

export default DS.Model.extend({
  firstName: DS.attr(),
  lastName: DS.attr(),
  fullName: Ember.computed('firstName', 'lastName', function() {
    return `${this.get('lastName')}, ${this.get('firstName')}`;
});

An Employee inherits from Person and adds a status field (like hired, retired, fired, etc.)

app/models/employee.js

import DS from 'ember-data';

import Person from '../models/person';

export default Person.extend({
  status: DS.attr(),
  statusCode: DS.attr(),
});

In a component that is displaying the Employees, like this:

app/templates/components/employee-list.hbs

{{#each employees as |employee|}}
<div>
  <h2>{{employee.fullName}}</h2>
  <p>Home Base : [city]</p>
  <p>Status : {{employee.status}}</p>
</div>
{{/each}}

What is the EmberJS way to get at the address of this Employee (ie. this 'Person') so that the template can show the city of this person from the Address model?


Solution

  • {{employee.address.city}} is the handlebars code that's needed:

    {{#each employees as |employee|}}
    <div>
      <h2>{{employee.fullName}}</h2>
      <p>Home Base : {{employee.address.city}}</p>
      <p>Status : {{employee.status}}</p>
    </div>
    {{/each}}