如何在Ember数据中嵌入一对一的关系?

Val*_*cev 5 ember.js ember-data

我正在使用Ember 1.0-pre4.

我有两种模式,一对一的关系:

App.Lesson = DS.Model.extend                               
  timeslot: DS.belongsTo 'App.Timeslot'

App.Timeslot = DS.Model.extend
  lesson: DS.belongsTo 'App.Lesson'
Run Code Online (Sandbox Code Playgroud)

我有一个适配器配置为在保存时将时隙嵌入课程中:

App.Adapter = DS.RESTAdapter.extend()  

App.Adapter.map App.Lesson,    
  timeslot: { embedded: 'always' }             

App.Store = DS.Store.extend            
  revision: 11                                 
  adapter: App.Adapter.create()       
Run Code Online (Sandbox Code Playgroud)

然后我创建一个课程和一个时间段并尝试保存它们:

lesson = App.Lesson.createRecord
  group: group
lesson.set('timeslot', App.Timeslot.createRecord())

lesson.store.commit()
Run Code Online (Sandbox Code Playgroud)

但是在保存时没有嵌入任何东西,我看到POST请求,一个用于课程,一个用于时间段.

我如何告诉Ember始终将时间段嵌入课程中?

ken*_*ken 3

我认为这是一个错误,你应该报告它。筛选源代码并进行一些测试表明,根本createRecord没有考虑配置。embedded该配置仅用于序列化和反序列化过程。

当您调用 createRecord 时,一条记录将添加到存储桶中,created并且commit ember-data只需在存储桶中的每条记录上触发一个 ajax post。

因此,回到您的代码,您创建了两条记录,并且在提交时它将为其中的对象ember-data触发一个ajax post调用,并且还将在后续调用中为最后一个剩余记录触发另一个ajax post调用在桶里。LessonTimeslot embeddedTimeslot

lesson = QrTimetable.Lesson.createRecord
  group: group

lesson.set('timeslot', QrTimetable.Timeslot.createRecord())
lesson.store.commit()
Run Code Online (Sandbox Code Playgroud)

除非对 ember-data 内部有更好了解的人与我的观点相矛盾,否则我倾向于再次相信这是一个错误。

这是提交事务时调用的最后一个代码。

  createRecord: function(store, type, record) {
    var root = this.rootForType(type);

    var data = {};
    data[root] = this.serialize(record, { includeId: true });

    this.ajax(this.buildURL(root), "POST", {
      data: data,
      context: this,
      success: function(json) {
        Ember.run(this, function(){
          this.didCreateRecord(store, type, record, json);
        });
      },
      error: function(xhr) {
        this.didError(store, type, record, xhr);
      }
    });
  },
Run Code Online (Sandbox Code Playgroud)