2014-02-27 42 views
6

我有一個博客應用程序,API調用用戶「Users」,但我的Ember模型是「Author」。保存到Ember服務器時更改模型的JSON根

App.Author = DS.Model.extend({ 
    name: DS.attr(), 
    posts: DS.hasMany('post', {async: true}), 
    email: DS.attr() 
}); 

我映射傳入的JSON與AuthorSerializer:

App.AuthorSerializer = DS.RESTSerializer.extend({ 
    normalizePayload: function(type, payload) { 
     return this.translateRootKey('user', 'author', payload); 
    }, 
    translateRootKey: function(server_word, client_word, payload) { 
     var response = {}, 
      key = payload[server_word] ? client_word : Ember.String.pluralize(client_word), 
      value = payload[server_word] ? payload[server_word] : payload[Ember.String.pluralize(server_word)]; 
     response[key] = value; 
     return response; 
    } 
}); 

但我無法弄清楚如何改變我的POST根/ PUT當我堅持到服務器。我希望我的根是「用戶」或「用戶」(取決於具體情況)。服務器目前得到這個從灰燼作爲它的參數:

{"author"=>{"name"=>"asdf", "email"=>"asdf"}, "user"=>{}} 

我如何告訴灰燼使用「用戶/秒」作爲我的鍵名與服務器通話是什麼時候?

例子:

{"user"=>{"name"=>"asdf", "email"=>"asdf"}} 

回答

5

我認爲你正在尋找serializeIntoHash鉤。

App.AuthorSerializer = DS.RESTSerializer.extend({ 
    serializeIntoHash: function(hash, type, record, options) { 
    hash["user"] = this.serialize(record, options); 
    } 
}); 
+0

這似乎在接收方,理查德A建議,下面,但問題涉及配置發送方。 –

+0

是的,這個鉤子在model.save()被髮送到服務器之前調用 –

+1

http://emberjs.com/api/data/classes/DS.RESTSerializer.html#method_serializeIntoHash 「您可以使用此方法定製序列化爲JSON的根鍵默認情況下,REST序列化程序發送駝峯化的根鍵。例如,您的服務器可能會期望使用下劃線的根對象。 –

相關問題