Ember.js commiting parent model with already existing child models

元气小坏坏 提交于 2019-12-14 03:43:45

问题


Cheers! For example I have three models:

App.Foo = DS.Model.extend({
  bars: DS.hasMany('App.Bar', {embedded:'always'}),
  bazes: DS.hasMany('App.Baz', {embedded:'always'})
});

App.Bar = DS.Model.extend({
  foo: DS.belongsTo('App.Foo')
});

App.Baz = DS.Model.extend({
  foo: DS.belongsTo('App.Foo)
});

And adapter mappings like these:

App.RESTSerializer = DS.RESTSerializer.extend({
  init: function() {
    this._super();

    this.map('App.Foo', {
      bars:{embedded: 'always'},
      bazes:{embedded: 'always'}
    })
  }
});

I'm saving child records first in separated transactions (github.com/emberjs/data/pull/440):

barTransaction = App.store.transaction();
bar = barTransaction.createRecord(App.Bar);

//later
bazTransaction = App.store.transaction();
baz = bazTransaction.createRecord(App.Baz);

//later
fooTransaction = App.store.transaction();
foo = fooTransaction.createRecord(App.Foo);

//later
foo.get('bars').addObject(bar);
foo.get('bazes').addObject(baz);
fooTransaction.commit();

I just want to know if it possible to save parent and all child records with one POST request? For now it's creating one POST request for every child record separately.


回答1:


I believe your issue is with an outdated way of mapping embedded records. This used to happen in the serializer, but is now happening on a map() on the adapter...

You can see the integration test here: https://github.com/emberjs/data/blob/master/packages/ember-data/tests/integration/embedded/embedded_saving_test.js#L50

I think something along these lines will work:

App.Foo = DS.Model.extend({
  bars: DS.hasMany('App.Bar'),
  bazes: DS.hasMany('App.Baz')
});

App.Bar = DS.Model.extend({
  foo: DS.belongsTo('App.Foo')
});

App.Baz = DS.Model.extend({
  foo: DS.belongsTo('App.Foo')
});

App.Adapter = DS.RESTAdapter.extend({..configs..});

App.Adapter.map('App.Foo', {
  bars:{embedded: 'always'},
  bazes:{embedded: 'always'}
})

This should POST to the api at: api.com/foo and include the bars and bazes



来源:https://stackoverflow.com/questions/15025618/ember-js-commiting-parent-model-with-already-existing-child-models

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