如何在ember-data中回滚对HasMany的更改

时间:2013-10-14 14:29:24

标签: ember.js ember-data

我有以下模特:

App.Parent = DS.Model.extend({
  foo: DS.attr('string'),
  children: DS.hasMany('child', {async: true})
});

App.Child = DS.Model.extend({
  bar: DS.attr('string')
});

我给他们填充了一些夹具数据:

App.ApplicationAdapter = DS.FixtureAdapter.extend();

App.Parent.FIXTURES = [
  {
    id:0,
    foo: 'parent',
    children: [0,1]
  }
];

App.Child.FIXTURES = [
  {
    id: 0,
    bar: 'child 0'
  },
  {
    id: 1,
    bar: 'child 1'
  },
  {
    id: 2,
    bar: 'child 2'
  }
];

在对children关系进行一些更改后,如何将children关系回滚到其最新保存的状态?

我通过以下方式将新孩子推送到manyArray:

this.store.find('child', 2).then(function(child){
  model.get('children').pushObject(child);
})

这确实改变了关系(我在视图中看到了新的孩子),但父记录不会变脏。因此,当我尝试model.rollback()时,它什么也没做。我还尝试了我在How to rollback relationship changes in EmberData找到的解决方案,它在回滚之前添加了model.send('becomeDirty'),但它没有帮助。

也许我正在以错误的方式将孩子添加到我的关系中?

谢谢!

4 个答案:

答案 0 :(得分:2)

我用它来回滚脏的相关记录。

App.ParentRoute = Ember.Route.extend 
  model: ->
    @get('store').createRecord('parent', child: @get('store').createRecord('child'))
  actions:
      willTransition: (transition) ->
        rollbackRecords(@)

rollbackRecords = (context) ->
  if context.get("controller.content.isDirty")
    relationships = Ember.get(App[context.get('controller').resourceName], "relationshipsByName")
    content = context.get('controller.content')
    relationships.forEach (name, relationship) ->
      relatedModel = content.get(name)
      relatedModel.rollback() if relatedModel? and relatedModel.get('isDirty')
    content.rollback()
  true

答案 1 :(得分:2)

以下是一些将回滚模型的代码,以及我使用的关系:

    var model = this.get('model');
    var relatedModel, relatedModels;
    model.constructor.eachRelationship(function (key, relationship) {
        if (relationship.kind === 'hasMany') {
            relatedModels = model.get(key);
            if (relatedModels) {
                relatedModels.invoke('rollback'); //since this is an array, need to call the rollback function differently
            }
        }
        else {
            relatedModel = model.get(key);
            if (relatedModel) {
                relatedModel.rollback();
            }
        }
    });
    model.rollback();

希望这有帮助

答案 2 :(得分:2)

我相信这里列出的其他答案只能部分解决这个问题。如果您添加新的相关模型或删除现有模型,回滚也应该反转这些模型,我相信其他答案不会解决这个问题。这是一个完整的解决方案,它为hasMany和belongsTo关系提供了正确的脏检查和完全回滚:

https://stackoverflow.com/a/27184207/188740

答案 3 :(得分:0)

我喜欢做好的事情。 model.reload() - 它会彻底扫除您未与服务器同步的所有更改。