Zaid Bin Irfan
Zaid Bin Irfan

Reputation: 330

Ember model mapping with Server response

I am using asp.net web api for getting JSON response.

public class Artist
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

    }

and my ember model looks like this

Music.Artist = DS.Model.extend({
    name:DS.attr('string'),
    age:DS.attr('number')
});

It is not mapping due to its case. When i make my model at the server side 'name' instead of 'Name' it works. Do i need to take care of casing also, or there is some method.

Another thing, it always require id, what if i have id by another name, eg. artist_id

Upvotes: 1

Views: 423

Answers (1)

Marcio Junior
Marcio Junior

Reputation: 19128

You can override both how ember-data process the attribute key and the id.

To change the attribute key override the keyForAttribute method, the attr is your model attribute, and the return is the related key coming from the json. Because you want to process "name" as "Name", Ember.String.capitalize will do the work.

To change the id, just override the primaryKey property.

Below is the custom serializer

App.ApplicationSerializer = DS.RESTSerializer.extend({
  primaryKey: 'Id',
  keyForAttribute: function(attr) { 
    return Ember.String.capitalize(attr);
  }
});

A live sample with this code can be found in http://emberjs.jsbin.com/OxIDiVU/950/edit

Upvotes: 1

Related Questions