2013-05-01 75 views
3

我的Rails應用程序用於生產JSON是這個樣子:格式化Ember的Rabl或將Ember映射到Rabl?

{"paintings": 
    [ 
    {"id":1,"name":"a"}, 
    {"id":2,"name":"b"} 
    ] 
} 

我加Rabl的JSON格式,而現在的JSON看起來是這樣的:

[ 
    {"id":1,"name":"a"}, 
    {"id":2,"name":"b"} 
] 

灰燼告訴我

Uncaught Error: assertion failed: Your server returned a hash with the key 0 but you have no mapping for it 

我該如何讓Ember理解這一點?或者我應該如何讓饒舌變得容易理解?

回答

1

您可以延長DS.RESTSerializer並更改extractextractMany。以下僅僅是一個副本,從我在.NET中使用串行粘貼,對於同樣的情形:

window.App = Ember.Application.create(); 
var adapter = DS.RESTAdapter.create(); 
var serializer = Ember.get(adapter, 'serializer'); 
serializer.reopen({ 
    extractMany: function (loader, json, type, records) { 
     var root = this.rootForType(type); 
     root = this.pluralize(root); 
     var objects; 

     if (json instanceof Array) { 
      objects = json; 
     } 
     else { 
      this.sideload(loader, type, json, root); 
      this.extractMeta(loader, type, json); 
      objects = json[root]; 
     } 

     if (objects) { 
      var references = []; 
      if (records) { records = records.toArray(); } 

      for (var i = 0; i < objects.length; i++) { 
       if (records) { loader.updateId(records[i], objects[i]); } 
       var reference = this.extractRecordRepresentation(loader, type, objects[i]); 
       references.push(reference); 
      } 

      loader.populateArray(references); 
     } 
    }, 
    extract: function (loader, json, type, record) { 
     if (record) loader.updateId(record, json); 
     this.extractRecordRepresentation(loader, type, json); 
    } 
}); 

並設置你的店前,您必須配置模型能夠正常側向載荷:

serializer.configure('App.Painting', { 
    sideloadAs: 'paintings' 
}); 

App.Store = DS.Store.extend({ 
    adapter: adapter, 
    revision: 12 
}); 

現在您應該可以將無根JSON負載加載到您的應用程序中。

(見fiddle

+0

謝謝你,這是我一直在尋找的答案。 – 2013-05-01 18:31:06

3

實測值的溶液中。我index.json.rabl是這樣的:

collection @paintings 
extends 'paintings/show' 

現在看起來是這樣的:

collection @paintings => :paintings 
extends 'paintings/show' 
+0

這實際上可能會更好,所以在這種情況下,您不必延長串行器 – MilkyWayJoe 2013-05-01 18:35:39

+0

是的,但我也試圖更好地理解串行器 – 2013-05-01 18:59:06