3

我的 rails 应用程序用于生成如下所示的 JSON:

{"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 明白这一点?或者我应该如何让 rabl 可以理解为 ember?

4

2 回答 2

3

找到了解决方案。我的 index.json.rabl 看起来像这样:

collection @paintings 
extends 'paintings/show'

现在看起来像这样:

collection @paintings => :paintings
extends 'paintings/show'
于 2013-05-01T18:28:22.473 回答
1

您可以扩展DS.RESTSerializer和更改extractand extractMany。以下只是我在 .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 有效负载加载到您的应用程序中。

(见小提琴

于 2013-05-01T18:26:32.627 回答