Thilina Dinith Fonseka
Thilina Dinith Fonseka

Reputation: 644

Ember 3.5 BelongsTo Relationships not Resolving

i used to have emberjs 1.13 which i upgraded to 3.5 i got an issue with belongsTo relationships where i cannot access those data in it. my code as below

model

export default DS.Model.extend( {

  title: DS.attr( 'string' ),
  description: DS.attr( 'string' ),
  published: DS.attr( 'boolean' ),
  publishedAt: DS.attr( 'date' ),

  course: DS.belongsTo( 'course' ),
  author: DS.belongsTo( 'profile', { async: true } ),

  viewed: false,
  isNew: true,

}

in controller

this.get('model.published') working 
this.get('model.author.name') not working 

but the same code was working on 1.13 of emberjs

with ember data 1.13

enter image description here

with ember data 3.5

enter image description here

Upvotes: 0

Views: 164

Answers (1)

Jan Werkhoven
Jan Werkhoven

Reputation: 2953

That's a big upgrade from 1.13 straight to 3.5.

A lot has changed. To fully understand what changed and why, I much recommend reading each of the Ember release notes every time you upgrade a minor or major version. Super helpful.

Most likely author was not loaded into the store. Check your route's model(), network request and Ember Inspector if data loaded in.

If loaded in, it may be the async: true. Try remove it?

This is a working example in Ember 3.5:

app/models/thing.js:

import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { belongsTo } from 'ember-data/relationships';

export default Model.extend({

  // Attributes
  title: attr('string'),
  description: attr('string'),
  published: attr('string'),
  publishedAt: attr('string'),

  // Relationships:
  // No need for async: true
  course: belongsTo('course'),
  author: belongsTo('author')

});

app/models/author.js:

import Model from 'ember-data/model';
import attr from 'ember-data/attr';

export default Model.extend({
  name: attr('string')
});

app/route/thing.js

import Route from '@ember/routing/route';

export default Route.extend({
  model(params) {
    // Assuming you use JSON API
    // Make sure `author` is included when fetching `thing`
    return this.store.query('thing', {
      include: 'author, course'
    }),
  }
});

app/controllers/thing.js

import Controller from '@ember/controller';

export default Controller.extend({
  init(){
    console.log(this.model.author.name)
  }
});

Upvotes: 1

Related Questions