Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a model's JSON root when saving to the sever in Ember

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"}}
like image 684
David Avatar asked Feb 27 '14 03:02

David


People also ask

What is the default serializer shipped with Ember?

Ember Data ships with 3 serializers. The JSONAPISerializer is the default serializer and works with JSON:API backends. The JSONSerializer is a simple serializer for working with single JSON object or arrays of records.

Why is Ember better than react?

When many elements are used in a project, it is preferable to use React JS due to its fast performance. Ember is considered to be one of the best in distributor logic. It provides the best combination with ember-data and the best CLI, which makes working with Ember much easier.

What are models in Ember?

In Ember Data, models are objects that represent the underlying data that your application presents to the user. Note that Ember Data models are a different concept than the model method on Routes, although they share the same name.


1 Answers

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);
  }
});
like image 84
Ryan Rauh Avatar answered Oct 04 '22 17:10

Ryan Rauh