Ember数据:保存多态关系

时间:2015-03-06 16:39:17

标签: ember.js ember-data

我无法在Ember Data(1.0.0-beta.15)中保存“hasMany”多态记录。看起来好像Ember Data没有设置多态关系的“type”属性。序列化记录中的关系如下所示:

"roles": ["1", "2"]

当我希望它们看起来更像:

"roles":[{
    "id": "1",
    "type": "professionalRole"
  }, {
    "id": "2",
    "type": "personalRole"
  }
];

我在控制台中看到以下错误:

  

TypeError:无法读取未定义

的属性'typeKey'

如果记录以预期的格式从服务器返回,一切都很好。只有在Ember Data创建关系时才会出现错误。

我使用FixtureAdapter,LocalStorageAdapter和RESTAdapter来体验这一点。我已经阅读了关于这个主题的每一篇文章,但我看不出我的错误。

我已经创建了一个CodePen来演示这个问题,但我也会在下面粘贴该代码。

window.App = Ember.Application.create();
App.ApplicationAdapter = DS.FixtureAdapter;

App.Person = DS.Model.extend({
  name: DS.attr(),
  roles: DS.hasMany('role')
});

App.Role = DS.Model.extend({
  title: DS.attr(),
  person: DS.belongsTo('person', {
    polymorphic: true
  })
});

App.ProfessionalRole = App.Role.extend({
  rank: DS.attr()
});

App.ApplicationRoute = Ember.Route.extend({
  setupController: function(controller) {
    var person = this.store.createRecord('person', {
      name: 'James'
    });
    var role = this.store.createRecord('professionalRole', {
      title: 'Code Reviewer',
      rank: 'Expert'
    });
    var promises = Ember.RSVP.hash({
      person: person.save(),
      role: role.save()
    });
    promises.catch(function() {
      controller.set('initialSaveResult', 'Failure');
    });
    promises.then(function(resolved) {
      controller.set('initialSaveResult', 'Success!');
      var resolvedPerson = resolved.person;
      var resolvedRole = resolved.role;

      // Either/both of these break it
      //resolvedRole.set('person', resolvedPerson);
      resolvedPerson.get('roles').addObject(resolvedRole);

      var innerPromises = Ember.RSVP.hash({
        person: resolvedPerson.save(),
        role: resolvedRole.save()
      });
      innerPromises.catch(function() {
        controller.set('secondSaveResult', 'Failure');
      });
      innerPromises.then(function() {
        controller.set('secondSaveResult', 'Success!');
      });
    });
  }
});

App.ApplicationController = Ember.Controller.extend({
  initialSaveResult: "Loading...",
  secondSaveResult: "Loading..."
});

0 个答案:

没有答案