如何在父模型中添加新的许多关系

How to add a new many relationship to parent model?

本文关键字:许多 关系 添加 模型      更新时间:2023-09-26

免责声明:我试图做一个jsfiddle,但没有RESTAdapter的公共源代码,我不能真正使它工作。

我有一个具有hasMany子模型数组的模型。我需要添加一个新模型到这个子数组并保存到服务器:

App.FooModel = DS.Model.extend({
  'name': DS.attr('string'),
  'bars': DS.hasMany('App.BarModel')
});
App.BarModel = DS.Model.extend({
  'name': DS.attr('string'),
});
App.ApplicationController = Ember.Controller.extend({
  init: function() {
    var foo    = App.FooModel.find(101); // -- currently has bars[201, 202, 203]
    var newBar = loadFixture( App.BarModel, 204 );
    var self = this;
    setTimeout( function() { // -- just to be sure our models are loaded before we try this
      // foo.currentState: saved
      foo.get('bars').addObject(newBar);
      // foo.currentState: saved
      foo.store.commit(); // -- nothing happens
    }, 1000);
  }
});
App = Ember.Application.create({
  store: DS.Store.create({
    revision: 11
  })
});

但是什么也没发生。我的父模型没有被标记为脏模型,因此存储永远不会尝试提交。我应该用别的方式把这个关系添加到父节点上吗?这是臭虫吗?

当前处理:

foo.get('bars').addObject(newBar);
var save = foo.get('name');    
foo.set('name', (save + '!'));
foo.set('name', save); // -- this marks our record as dirty, so a save will actually happen
foo.store.commit();

Edit 1:我知道ember-data只会序列化这个数据,如果它开始嵌入(https://stackoverflow.com/a/15145803/84762),但是我已经覆盖了我的序列化器来处理这个问题。我遇到的问题是,存储甚至从来没有尝试保存这个更改,所以我们甚至从来没有到达序列化器。

编辑2:我怀疑这个可能与这个bug有关,但同时这也意味着这对任何人都不起作用,我很难相信没有人遇到过这种情况,

看起来您正在建模一对多的关系,但您没有在App.BarModel上包含belongsTo选项。查看此链接:

http://emberjs.com/guides/models/defining-models/toc_one-to-many

App.Post = DS.Model.extend({
    comments: DS.hasMany('App.Comment')
});
App.Comment = DS.Model.extend({
    post: DS.belongsTo('App.Post')
});

据我所知,您没有使用embedded的关系特性,而是覆盖了您的序列化器来处理bars对象到foo对象的序列化。

我认为你的错误可能来自这里:如果你的关系没有嵌入,没有理由把foo对象标记为脏的,因为当你添加一个对象到他的bars关联时,应该改变的通常是你添加的bar对象的关键foo_id,那么foo对象就没有变化发送到API。