I need to side load a model into Ember Data's store. An example of why I need to do this is because the properties that need to be sent to the server when creating a model is different from what needs to be sent when updating a model. Here's a simple example:
POST /api/users
{
"user": {
"firstName": "Mark",
"lastName": "Jones",
"password":"my-secret-password",
"confirmPassword":"my-secret-password"
}
}
PUT /api/users/1
{
"user": {
"firstName": "Mark",
"lastName": "Jones"
}
}
Both POST and PUT endpoints will return the same payload:
{
"user": {
"id":1
"firstName": "Mark",
"lastName": "Jones"
}
}
But notice that POST expects 'password' and 'confirmPassword' while PUT doesn't. Also, I don't want 'password' and 'confirmPassword' to be part of the App.User model since it's only used when creating a user. Since Ember Data doesn't support different payloads for different HTTP Verbs, I'm using basic jQuery to send an ajax POST request, and upon success, doing something like this in the controller. Note that the model for this controller is simply an Ember.Object.
actions: {
save: function () {
var that = this;
$.ajax({
type: 'POST',
url: '/api/users',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({
user: this.getProperties('firstName', 'lastName')
})
}).done(function (data, textStatus, jqXHR) {
var user = that.store.createRecord('user', data.user);
that.transitionToRoute('user', user);
});
}
}
The problem with this approach is that new model's isNew and isDirty properties are 'true'. How do I change the state of the model so that Ember Data's store believes that the model is clean and reflects the state of the server?
I've tried this:
user.adapterWillCommit();
user.set('_attributes', {});
user.adapterDidCommit();
...while it changed both isNew and isDirty to 'false', it didn't prevent user.rollback() (which I use elsewhere in the application) from rolling back all property values back to 'undefined'.
I also tried this:
user.reload();
...but even after reloading the model, Ember Data tries to 'POST' when calling user.save() instead of 'PUT'. I obviously don't want to make a POST request when editing this user, as the server will attempt to create another user.
Any way update the state of a model to let Ember Data know what it reflects the state of the server?