在Ember.js中保存OneToMany关系的问题

时间:2014-09-08 12:01:05

标签: ember.js ember-data

我们正在使用标准RestAdapter的Ember-Data,到目前为止一直很好。我们可以使用OneToOne和ManyToMany关系保存对象,但是当我们尝试使用OneToMany关系保存对象时,在调用save()时会丢弃添加到多方的任何对象。代码如下:

2个型号:

Ember.Owner = DS.Model.extend({
  name: DS.attr('string'),
  pets: DS.hasMany('pet', {async: true});
});

Ember.Pet = DS.Model.extend({
  name: DS.attr('string'),
  owner: DS.belongsTo('owner', {async: true});
});

控制器代码:

actions: {

        save:  function() {

            var self = this;

            var petSaved = function(pet) {

                 // Create the owner
                 var owner = self.store.createRecord ('owner', {
                        name: 'Walt',
                 });

                // Add the new pet then save the owner
                owner.get('pets').then(function(pets) {
                    pets.addObject(pet);
                    // Logging the owner at this point shows that pet has been added and has been assigned an id from the DB
                    owner.save();
                    // Logging the owner at this point shows no pets
                });
            };

            // Create the pet
            var pet = this.store.createRecord('pet', {
                name: 'Lassie',
            });

            // Save the pet
            pet.save().then(petSaved);
        },
    },

使用与上面基本类似的代码,我们可以成功保存ManyToMany和OneToOne关系,但由于某种原因,此代码失败。经过大量谷歌搜索,我们已经读到这是EmberData错误或Ember明确的设计决策,因为效率考虑,但后者没有意义,因为ManyToMany关系可以这样保存。

我们非常感谢对此问题的任何见解以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您需要将DS.EmbeddedRecordsMixin加入App.OwnerSerializer

应该看起来像......

App.OwnerSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    pets: {serialize: 'ids', deserialize: 'ids'}
  }
})