Determine if hasMany -> belongsTo item has been created in Ember.js

試著忘記壹切 提交于 2019-12-12 02:34:31

问题


I'm using Ember: 1.3.0-beta.2 and Ember Data: 1.0.0-beta.2

Here's my setup:

Models

Rise.User = DS.Model.extend({
  //....
  user_training_plans: DS.hasMany('training_plan', { async: true }),
  user_training_histories: DS.hasMany('training_history', { async: true }),
});

Rise.TrainingHistory = DS.Model.extend({
  //....
  user: DS.belongsTo('user', { async: true }),
  training_resource: DS.belongsTo('training_resource', { async: true })
});

Rise.TrainingPlan = DS.Model.extend({
  //....
  user: DS.belongsTo('user', { async: true }),
  training_resource: DS.belongsTo('training_resource', { async: true })
});

In a controller action, I'm trying to "move" a training resource from a user's training plan to training histories. I'd like to determine if the training resource has already been added to training histories before adding it.

I'd like to do something like this, which is currently in the training plans route

markCompleted: function(trainingPlanItem) {
  completed_training_resource_id = trainingPlanItem.get('training_resource.id');

  this.controller.get('user_training_histories').then( function(user_training_histories) {
    var already_exists = user_training_histories.any( function(item) {
      var item_id = item.get('training_resource').get('id');
      if (item_id == completed_training_resource_id) {
        return true;
      }
    });

    // ...continues
  });
}

Of course, item.get('training_resource').get('id'); returns a promise if the data has not been fetched, so this if (item_id == completed_training_resource_id) comparison line doesn't work correctly.

Is there a way to run any and use a promise inside? Or is there a way to see the training_resource_id without loading the training resource? This is a belongs_to relationship, so the training resource id is fetched from the server.


回答1:


Get belongsTo ID without fetching record

I'm not sure if i agree with this route, but you can grab it off the data obj

item.get('data.training_resource.id')


来源:https://stackoverflow.com/questions/20569378/determine-if-hasmany-belongsto-item-has-been-created-in-ember-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!