dimanche 29 janvier 2017

How to load nested records (master-detail records) using Ember Data?

The master record, app/models/account:

import DS from 'ember-data';

export default DS.Model.extend({
  username: DS.attr('string'),
  emailaddress: DS.hasMany('emailaddresses'),
  birthdate: DS.attr('date'),
  gender: DS.attr('boolean')
});

The detail record, app/models/emailaddress:

import DS from 'ember-data';

export default DS.Model.extend({
  account: DS.belongsTo('account'),
  emailaddress: DS.attr('string'),
  verificationcode: DS.attr('string'),
  isverified: DS.attr('string')
});

The dummy JSON string from the server:

{"id":0,"username":"ikevin","birthdate":"Jan 30, 2017 1:34:38 PM","gender":true,"emailaddresses":[{"id":0,"emailaddress":"aaa@bbb.com","verificationcode":"AAAAAA","isverified":false}]}

The adapter /app/adapters/account.js

import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({

  urlForQueryRecord(query) {
    if (query.profile) {
      delete query.profile;
      return `${this._super(...arguments)}/profile`;
    }

    return this._super(...arguments);
  }

});

The route app/route/index.js:

import Ember from 'ember';
import RSVP from 'rsvp';

export default Ember.Route.extend({
  model() {
    return RSVP.hash({
      walletbalance: this.get('store').queryRecord('wallet', {balance: true}),
      instagramfriendscount: this.get('store').queryRecord('instagram', {friendscount: true}),
      accountprofile: this.get('store').queryRecord('account', {profile: true})
    });
  }
});

And the app/templates/components/account-profile.hbs:

<div class="box">
  <div class="title">Your Profile</div>
  <div>Username: </div>
  <div>Email Address: </div>
  <div>Birthdate: </div>
  <div>Gender: </div>
</div>

I think there are 2 problems here:

  1. In the Chrome Ember plugin, the data for model type "emailaddress" is always 0. So, that means it is not loaded.

  2. In the app/templates/components/account-profile.hbs, is not referring to the correct field. Note: for now it is expected to display only 1 email address.

How do I resolve these problems to load and display nested records?

Thanks!




Aucun commentaire:

Enregistrer un commentaire