Search code examples
ember.jsember-dataember-cli

Ember resolving async belongsTo to null


Using the following component in ember-cli (component name if-current-user) the promise for a belongsTo on model.user resolves to null until I save an unrelated model into the store. How do I get it to resolve to the User object associated with the record?

export default Ember.Component.extend({
  userId: Ember.computed.alias('user.id'),
  currentUserId: Ember.computed.alias('session.user.id'),

  isCurrentUser: function() {
    return !!(this.get('userId') && this.get('currentUserId') && this.get('userId') === this.get('currentUserId'));
  }.property('userId', 'currentUserId')
});

Model:

import DS from 'ember-data';

export default DS.Model.extend({
  user: DS.belongsTo('user', { async: true }),
  timestamp: DS.attr('number')
});

Template:

{{#if-current-user user=model.user}}
  {{#link-to "route.edit" model}}Edit{{/link-to}}
{{/if-current-user}}

Note that I'm injecting the current session into all components, routes and controllers.


Solution

  • Turns out this was related to the data store on the backend. If you don't fulfil the requirements for hasMany / belongTo and do not insert the related instance into both objects, then this condition will represent itself.

    In short, I was only storing the current user in the belongsTo, and the inverse hasMany - when loading the user - couldn't find the relationship and seems to remove it from the Ember Data store. Annoying, but at least it is consistent.

    import Ember from 'ember';
    
    export default Ember.Controller.extend({
      actions: {
        save: function() {
          var user = this.get('session.user');
          var newInstance = this.store.createRecord('model', {
            user: user,
            timestamp: new Date().getTime()
          });
          newInstance.save().then(function() {
            user.get('models').pushObject(newInstance);
            user.save();
          });
        }
      }
    });