7
votes

I have a blog application where the API calls the users "Users", but my Ember model is "Author".

App.Author = DS.Model.extend({
    name: DS.attr(),
    posts: DS.hasMany('post', {async: true}),
    email: DS.attr()
});

I map incoming JSON with an AuthorSerializer:

App.AuthorSerializer = DS.RESTSerializer.extend({
    normalizePayload: function(type, payload) {
        return this.translateRootKey('user', 'author', payload);
    },
    translateRootKey: function(server_word, client_word, payload) {
        var response = {},
            key = payload[server_word] ? client_word : Ember.String.pluralize(client_word),
            value = payload[server_word] ? payload[server_word] : payload[Ember.String.pluralize(server_word)];
        response[key] = value;
        return response;
    }
});

But I can't figure out how to change the root of my POST/PUT when I'm persisting to the server. I want my root to be "user" or "users" (depending on the situation). The server is currently getting this from Ember as its parameters:

{"author"=>{"name"=>"asdf", "email"=>"asdf"}, "user"=>{}}

How do I tell Ember to use "user/s" as my key name when talking to the server?

Example:

{"user"=>{"name"=>"asdf", "email"=>"asdf"}}
1

1 Answers

6
votes

I think you are looking for the serializeIntoHash hook.

App.AuthorSerializer = DS.RESTSerializer.extend({
  serializeIntoHash: function(hash, type, record, options) {
    hash["user"] = this.serialize(record, options);
  }
});