【问题标题】:How to prevent CreateRecord and Commit from duplicating records in Ember.js?如何防止 CreateRecord 和 Commit 在 Ember.js 中复制记录?
【发布时间】:2026-02-02 12:10:01
【问题描述】:

我在 Ember.js 中创建了一个简单的控制器,其目的是将一个人添加到商店,使用 REST 适配器将其保存到服务器并获取 ID 并使用 ID 更新行。

我的代码如下所示:

App.AddPersonController = Ember.ObjectController.extend({
  newRecord: function() {
       currentRecord = App.Person.createRecord({name: "Abraham"});
       this.set('content', currentRecord );
  }
  save : function() {
      var result = this.get('store').commit();
      this.transitionToRoute('people.list');
      return result;
  }
});

我调用 newRecord() 并用 Abraham 创建了新记录。接下来,我允许用户编辑名称。在他推动保存后,我以这种方式从模板调用保存函数:

{{action save on="submit"}}

新记录作为一行正确保存到数据库中。用户被重定向到人员列表。但突然间,似乎在人名单上亚伯拉罕是重复的。

我调查了商店,有两行具有相同的数据和相同的 ID。用户名不同。数据库中只有一行。

那么在这种情况下如何防止 Ember.js 重复添加的行呢?

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    由于您正在寻找详细的规范答案,我将假设您想做“The Ember Way”。

    假设这是您的Person 模型:

    App.Person = DS.Model.extend({
      firstName : DS.attr('string'),
      lastName  : DS.attr('string')
    });
    

    通常,您需要使用 Routemodel 挂钩来设置控制器的内容。

    App.AddPersonRoute = Ember.Route.extend({
      model : function(){
        return this.store.createRecord('person',{
          firstName : 'fake', 
          lastName : 'name'
        });
      }
    });
    

    然后在您的Controller 中,您只需检索content 对象,调用save,然后转换到您想去的地方。

    App.AddPersonController = Ember.ObjectController.extend({
      actions : {
        save : function(){
          this.get('model').save();
          this.transitionToRoute('index');
        }
      }
    });
    

    这是一个 JSBin,它使用 FixtureController 展示了这一点:http://jsbin.com/ucanam/1201/edit

    【讨论】:

      【解决方案2】:

      因为唱片永远不会在商店里。这样做实际上应该会出错。

      创建新记录的正确方法是

      currentRecord = this.store.createRecord('person');
      

      然后将该记录保存出来:

      currentRecord.save();
      

      【讨论】: