2013-03-16 46 views
1

我有以下型號:創建父和子模型提交

App.Offers = DS.Model.extend({ 
    name: DS.attr('string'),    
    createdBy: DS.belongsTo('App.Users'), 
    products: DS.hasMany('App.Products'), 
    startDate: DS.attr('string'), 
    endDate: DS.attr('string') 
} 

App.Products = DS.Model.extend({ 
    description: DS.attr('string'), 
    img: DS.attr('string'), 
    offer: DS.belongsTo('App.Offers'), 
} 

使用這兩款車型我同時創建一個報價(父)和產品(子):

var offer = App.Offers.createRecord({/*fields*/}), 
    product = App.Products.createRecord({/*fields*/}); 
offer.get('products').pushObject(product); 
offer.get("store").commit(); 

當我這樣做時,問題在於父母需要孩子的ID,而孩子需要父母的ID才能設置其FK。

我查了一下ember-data回購中的問題和PR,我發現這個:https://github.com/emberjs/data/pull/440。它建議在一個waitForParents函數中包裝createRecord,該函數基本上創建了父項,然後是子項。儘管我已經嘗試過他們的建議,但我仍然無法創建我的記錄。問題是,即使對父進程的請求是先做出來的,仍然需要子進程的標識(尚未創建)。父請求發送時攜帶以下有效負載:

{/*other_fields*/,"products":["/api/v1/products//"]} 

請注意URL中產品的缺失ID。

回答

0

我設法通過遵循此PR中的建議來解決它:https://github.com/emberjs/data/issues/437。他們基本上建議創建一個waitForParents函數並將其包裝在createRecord中。該函數檢查是否存在belongsTo關係,並推遲該創建的代碼執行,直至創建父代(通過向id字段添加觀察者)。

在我的情況下,我不得不重寫序列化器中的addHasMany。

我希望能幫助其他人解決同樣的問題。