Ember Data not serializing record id on save(), resulting in PUT with no id?

ember-data, ember.js, javascript

Solution

The base JSONSerializer in Ember-Data only includes id in the payload when creating records. See DS.JSONAdapter.serialize docs.

The URL the RestAdapter generates for PUTting the update includes the ID in the path. In your case I believe it would be: `PUT '/services/102'`.

You can either extract it from the path in your backend service. Or you should be able to override the behavior of your serializer to add the id like this:

App.ServiceSerializer = DS.JSONSerializer.extend({
  serialize: function(record, options) {
    var json = this._super.apply(this, arguments); // Get default serialization

    json.id = record.id;  // tack on the id

    return json;
  }
});

There's plenty of additional info on serialization customization in the docs.

Hope that helps!

Problem

I have a route that creates a new record like so: ``` App.ServicesNewRoute = Ember.Route.extend({ model : function() { return this.store.createRecord('service'); }, setupController: function(controller, model) { controller.set('model', model); }, }); ``` Then I bind that model's properties to the route's template using `{{input type="text" value=model.serviceId ... }}` which works great, the model gets populated as I fill up the form. Then I save record: ``` App.ServicesNewController = Ember.ObjectController.extend({ actions : { saveService : function() { this.get('model').save(); // => POST to '/services' } } }); ``` Which works too. Then I click the save button again, now the save method does a PUT as expected since the model has an id set (id: 102): But then when I look at the PUT request in Dev Tools, I see that the id attribute was not serialized: As a result, a new instance is created in the backend instead of updating the existing one. Please ignore the serviceId property, it is just a regular `string` property unrelated to the record id which should be named just `id`. I don't know why the `id` is not being serialized... I cannot define an id property on the model of course since Ember Data will not allow it, it is implicit. So I don't know what I am missing... Any help is greatly appreciated!

Original source