4
votes

I'm beginning to work with ember-data and I have a problem to map the data

Here an exemple of my code ( i've place a jsonTest as an exemple of the data received from de backend , I don't work on the backend and I cannot modify the response from the server )

Clive = Ember.Application.create();
// MODEL


Clive.Deadline = DS.Model.extend({
    title : DS.attr('string'),
});

jsonTest = '{"items":[{"id":93,"title":"title","date":"14-11-2012"}]}';

// Adapter 
Clive.adapter = DS.Adapter.create({
    findAll : function(store,type){
        var  self = this;        
        self.didFindAll(store, type, jsonTest);
    }
});

Clive.store = DS.Store.create({
  revision: 11,
  adapter: 'Clive.adapter'
});

Clive.deadlineList = Clive.Deadline.find().get('items');

When I run the code I have this error :

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

Here a jsfidlle with the exemple : http://jsfiddle.net/gilles/6D5BC/

2
Been there.. Maybe this will help. Also, read about the JSON format that Ember-Data likes here.MilkyWayJoe

2 Answers

5
votes

The "server returned a hash with key 0" thing is because didFindAll() expects a javascript object not a string. So trying again with:

json = {"items":[{"id":93,"title":"title","date":"14-11-2012"}]};
// -> "Your server returned a hash with the key items but you have no mapping for it"

Next step is to transform the object to have naming conventions that ember is expecting. Since your model is named Deadline, use the following:

jsonTransformed = '{"deadlines": [{"id":93,"title":"title 1","date":"14-11-2012"},{"id":94,"title":"title 2","date":"14-11-2012"}]}';

I've added a second record, but you get the idea. Finally you need to change how the Clive.deadlineList variable is being set: Clive.Deadline.find() returns a collection of Clive.Deadline models, so just:

Clive.deadlineList = Clive.Deadline.find()
console.log(Clive.deadlineList.getEach('title'));
// -> title1, title2

Here is an updated jsfiddle with working example: http://jsfiddle.net/mgrassotti/6D5BC/9/

1
votes

Another simple solution is to use the following Gem. It will just make your life easier. You wont need to generate or structure the json manually.

gem 'active_model_serializers'

For more help, have a look on this free screencast