3

My rails app used to produce JSON that looked like this:

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

I added rabl json formatting, and now the json looks like this:

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

Ember is telling me

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

How can I make Ember understand this? Or how should I make rabl understandable to ember?

CraigTeegarden
  • 8,173
  • 8
  • 38
  • 43
Dan Baker
  • 1,757
  • 3
  • 21
  • 36

2 Answers2

3

Found a solution. My index.json.rabl looked like this:

collection @paintings 
extends 'paintings/show'

Now it looks like this:

collection @paintings => :paintings
extends 'paintings/show'
Dan Baker
  • 1,757
  • 3
  • 21
  • 36
1

You can extend DS.RESTSerializer and change extract and extractMany. The following is merely a copy and paste from the serializer I use in .NET, for the same scenario:

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);
    }
});

And before you set your store, you must configure your model to sideload properly:

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

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

Now you should be able to load rootless JSON payload into your app.

(see fiddle)

MilkyWayJoe
  • 9,082
  • 2
  • 38
  • 53