2013-11-24 30 views
1

我有一套名爲ProfileTag的模型。配置文件可以有很多標籤,並且標籤可以屬於多個配置文件。我的模型設置如下:Ember.js保存多對多關係到服務器

App.Profile = DS.Model.extend({ 
    name: DS.attr(), 
    tags: DS.hasMany('tag') 
}); 

App.Tag = DS.Model.extend({ 
    title: DS.attr(), 
    profile: DS.hasMany('profile') 
}); 

我寫了下面的代碼來測試關係和數據提交到服務器:

var profile = this.store.createRecord('profile', { 
    name: 'John Doe' 
}); 

var tag1 = this.store.createRecord('tag', { 
    title: 'Tag 1' 
}); 

var tag2 = this.store.createRecord('tag', { 
    title: 'Tag 2' 
}); 

var tag3 = this.store.createRecord('tag', { 
    title: 'Tag 3' 
}); 

profile.get('tags').pushObject(tag1); 
profile.get('tags').pushObject(tag2); 
profile.get('tags').pushObject(tag3); 

profile.save(); 

然而,關係永遠不會發送到服務器,即使我先保存標籤,然後再保存配置文件。

無論什麼數據灰燼POST到/profiles/總是包含"tags": [ null, null, null ]

編輯:我是救了我的模型以錯誤的方式,此代碼的工作對我來說:

profile.get('tags').save().then(function() { 

    profile.save(); 

}); 

回答

1

當你保存它保存了配置文件的名稱和標籤的ID。默認發送時,關係不會嵌入到json中。它發送標籤的id,它是空的。您需要首先保存標籤(並且您的服務器需要返回一個id,通常它會返回帶有id的整個模型)。然後當你保存個人資料時,ID將被髮送。如果你只想硬編碼一對夫婦,看看它是如何工作的,只需輸入id即可。

var tag1 = this.store.createRecord('tag', { 
    title: 'Tag 1', 
    id:21838123823 
}); 

之所以這麼說,你可以創建,如果你想發送的一切行動自定義序列,但是這是默認其餘的適配器/串行工作不是如何。

+0

謝謝,原來我是以錯誤的方式保存標籤。 –