Belongs to relationship id not in sync with relation object


I’m fairly new to ember and ember-data and have been struggling with what is the correct approach towards handling ids on belongsTo associations.

A simple setup of my problem would be

var Parent = DS.Model.extend({});
var Child = DS.Model.extend({
  parent: DS.belongsTo('parent', {async: true}),
  parentId: DS.attr() // also tried adding this

I would like to access the parentId instead of loading the entire model in some situations but in others I would like to access the parent object. The problem is get(‘parentId’) is not always equal to get(‘’). I’ve thought of implementing synchronization but this seems like a functionality that may be built in. Am I missing something here?

example access scenario

childInstance ='child', {parent: parentInstance});
childInstance.get('parentId') === childInstance.get(''); //=> false


childInstance ='child', childId);
  childInstance.get('parentId') === childInstance.get(''); //=> false

I had trouble setting this up with fixtures so no JSBin for this one


The minimum required:

var Item = DS.Model.extend({
  children: DS.hasMany('item', { async: true }),
  parentId: DS.attr('string')

Better to instead have:

var Item = DS.Model.extend({
  children: DS.hasMany('item', { inverse: 'parent' }),
  parent: DS.belongsTo('item', { inverse: 'children'}),

  // parentId can stay on model as an attribute:
  parentId: DS.attr('string')

  // else you can apply a computed value that exists only
  // on the client - ie: won't be saved to server
  parentId: Ember.computed('parent', function() {
      var parent = this.get('parent');
      return parent.get('id');

For future reference, this is called recursive association. Will help for future web searches.