简体   繁体   中英

Ember-data computed property on an async relationship

I have some models set up with async relationships, eg:

User = DS.Model({
    postsApproved: DS.hasMany('post', {async: true, inverse: 'approved'})
})

Post = DS.Model({
    approver: DS.belongsTo('user', {async: true, inverse: 'postsApproved'})
})

In a controller, I have a property on the post, isApproved , which simply checks if approver is set. I expect that this should work:

isApproved: function() {
    return !Ember.isNone(this.get('approver'));
}

But that always returns true, and if I inspect the data I see that it is because this.get('approver') returns a promise. This works:

isApproved: function() {
    return !Ember.isNone(this.get('approver.content'));
}

But using content seems to me to be messing around with the internals a bit too much. Is this the right way to do it, or am I missing something?

You are right, testing for this.get('approver.content') is not correct, as the element may actually have an associated approver , but it may not be loaded yet.

Try to load the related model on the route:

// route.js
model: function(params) {
   return this.store.find('post', params.post_id).then(function(post) {
     return Ember.RSVP.hash({
       post: post,
       approver: post.get('approver')
     });
   });
},

setupController: function(controller, model) {
  controller.set('model', model.post);
  controller.set('approver', model.approver);
},

// controller.js
isApproved: function() {
    return !Ember.isNone(this.get('approver'));
}.property('approver')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM