2016-03-30 48 views
1

很多關於此主題的其他帖子都是2+歲,所以這裏有一個潛在的簡單問題。Ember數據依賴鍵未定義

我正在使用Ember數據關係來使'bizinfo'記錄屬於'用戶'記錄。看起來很簡單,但我有最糟糕的時間。

在應用程序/模型/ bizinfo.js我也行:

'ownedBy': DS.belongsTo('user') 

而在我的路線,我在那裏驗證,然後保存模型,我有以下代碼:

user_id: Ember.computed(function(){ 
    return `${this.get('session.data.authenticated.user_id')}`; 
    }), 

    user: Ember.computed(function(){ 
    return this.store.findRecord('user', this.get('user_id')); 
    }), 

    model(params){ 
    return this.store.createRecord('bizinfo', {'ownedBy': this.get('user')}); 
    }, 

在這一點上,如果我進入灰燼檢查看看「商業信息」的數據對象,我看到了屬於關聯選項卡下的以下內容:

ownedBy : <(subclass of Ember.ObjectProxy):ember1053> 

下面是代碼從我提交一份行動:

submit() { 
    let model = this.currentModel; 
    console.log(model.ownedBy); 
    console.log(`what does the model look like?`); 
    console.log(model.toJSON()); 
    model.validate().then(({model, validations}) => { 
    if (validations.get('isValid')) { 
     this.setProperties({ 
     showAlert: false, 
     isRegistered: true, 
     showCode: false 
     }); 
     let success = (response) => { 
     console.log(`Server responded with ${response.toJSON()}`); 
     }; 

     let failure = (response) => { 
     console.log(`Server responded with ${response}`); 
     }; 
     model.save().then(success, failure); 
    } else { 
     this.set('showAlert', true); 
    } 
    this.set('didValidate', true); 
    }, (errors) => { 
    console.log(`errors from failed validation: ${errors}`); 
    }); 
}, 

因此,這裏是第一的console.log語句的結果:

​​

當我看model.toJSON()日誌,我看到

ownedBy: null 

任何人都可以看到這裏出了什麼問題嗎?它是創建記錄語句嗎?我已經嘗試了很多不同的排列(如提交剛好ID爲「用戶」的參數。

回答

2

findRecord會返回一個承諾,一個簡單的辦法來解決這個問題是

model(params){ 
    return this.store.findRecord('user', this.get('user_id')) . 
    then(ownedBy => this.store.createRecord('bizinfo', {ownedBy}); 
} 

這將等待findRecord解決,然後返回一個新的記錄與解決的值爲ownedBy屬性。

+1

Woohoo!你是一個生命保護者Tora-san。m(_ _)m –