2013-12-10 168 views
3

我試圖存儲與屬於關聯的關聯記錄,但相關的ID總是空:createRecord與屬於關聯關聯

客戶模式

Docket.Customer = DS.Model.extend({ 
    name:  DS.attr('string'), 
    initial:  DS.attr('string'), 
    description: DS.attr('string'), 
    number:  DS.attr('string'), 
    archived: DS.attr('boolean'), 
    projects: DS.hasMany('project',{ async: true }) 
}); 

項目模型

Docket.Project = DS.Model.extend({ 
    name:  DS.attr('string'), 
    description: DS.attr('string'), 
    number:  DS.attr('string'), 
    archived: DS.attr('boolean'), 
    customer: DS.belongsTo('customer') 
}); 

在ProjectsController中保存操作

var _this = this; 

// create new record 
var project = this.store.createRecord('project', this.getProperties('name','number', 'description', 'archived')); 

// add customer with id 22 to project 
this.store.find('customer', 22).then(function(customer) { 
    project.set('customer', customer); 
}); 

// save if validation passes, otherwise show errors 
project.save().then(function(){ 
    _this.resetAndCloseForm(form); 
}, function(response){ 
    _this.set('errors',response.errors); 
}); 

sended到服務器的JSON始終是這樣的:

archived: false 
customer_id: null 
description: null 
name: "foobar" 
number: null 

我想選擇一個選擇框項目的客戶。有沒有什麼聰明的方法讓選定的客戶成爲記錄,還是必須通過ID加載?

{{view Ember.Select 
    viewName="select" 
    contentBinding="customers" 
    optionLabelPath="content.name" 
    optionValuePath="content.id" 
    prompt="Pick a customer:" 
    selectionBinding="selectedCustomer" 
}} 
+0

我有同樣的問題,你能告訴我怎麼解決了這一問題? – JeskTop

回答

2

這是一個老版本的餘燼的數據,或者你有一個自定義序列化,因爲它應該發送它沒有_id。嘗試升級或顯示您的序列化程序。

並且在查找解決之前您正在保存。

// add customer with id 22 to project 
this.store.find('customer', 22).then(function(customer) { 
    project.set('customer', customer); 


    // save if validation passes, otherwise show errors 
    project.save().then(function(){ 
    _this.resetAndCloseForm(form); 
    }, function(response){ 
    _this.set('errors',response.errors); 
    }); 

}); 

它看起來像selectedCustomer有記錄。

// create new record 
var project = this.store.createRecord('project', this.getProperties('name','number', 'description', 'archived')); 

project.set('customer', this.get('selectedCustomer')); 

// save if validation passes, otherwise show errors 
project.save().then(function(){ 
    _this.resetAndCloseForm(form); 
}, function(response){ 
    _this.set('errors',response.errors); 
}); 

您還可以設置optionValuePath='content'

+0

是的,我現在在查找解決後保存記錄,但我想知道是否有更簡單的方法來做到這一點。有什麼方法可以直接從選擇框獲取客戶記錄嗎?我正在使用Ember Data 1.0.0 Beta 4.我正在使用'App.ApplicationSerializer = DS.ActiveModelSerializer.extend({});'此外,我希望Ember發送'customer_id'到我的API。 – Slevin

+0

是的,如果該選擇範圍內,請參閱編輯 – Kingpin2k

+0

工程就像一個魅力:) – Slevin