【问题标题】:Not able to create a new record无法创建新记录
【发布时间】:2014-12-13 16:24:20
【问题描述】:

我已经尝试了无数个小时来完成这项工作。我无法在网上找到我可以理解的答案。像我这样的其他初学者可能会遇到与我相同的问题,所以我发布了我的问题:

我的 Ember 应用程序出现此错误: 未捕获的错误:断言失败:您只能将“用户”记录添加到此关系中

我正在尝试创建“Cond”的新记录。但我无法将“用户”对象添加到新创建的 Cond 实例的用户属性中。但是,从 Chrome 调试工具中,我可以看到“用户”不是 null 或未定义。这是崩溃的控制器:

    App.BookController = Ember.Controller.extend({
      needs: 'user',
      user: Ember.computed.alias("controllers.user"),

      frequency: ['Every Minute', 'Every Hour', 'Every Day', 'Every Week', 'Every Month', 'Every Quarter', 'Every Year', 'Continuous'],
      selectedFrequency: 'Every Month',

      actions: {
        createCond: function() {

          var user = this.get('user');

          var Cond = this.store.createRecord('Cond', {
            name: this.get('name'),
            frequency: this.get('selectedFrequency'),
            description: this.get('description'),
            createdDate: new Date(),
          });

          Cond.set('user', user);  // Application crash her
          user.addObject('Conds', Cond);

          Cond.save().then(function() {  
            user.save();
            console.log('new Cond created');
          });
        }
      }

    });

感谢您的帮助!

【问题讨论】:

    标签: javascript ember.js ember-data


    【解决方案1】:

    您抓取用户控制器,模型是控制器上的一个属性。

    要么将别名更改为:

    user: Ember.computed.alias("controllers.user.model"),
    

    或将您的获取更改为:

    var user = this.get('user.model');
    

    【讨论】:

    • 效果很好。感谢金品客!为了其他用户的利益,请注意我的代码中有另一个错误:'user.addObject('Conds', Cond);'应该改为:user.get('conds').pushObject(cond);
    猜你喜欢
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多