6

From the ember docs its clear you should be able to save a dirty model

var m = App.MyModel.find(10) ;
...
m.set("firstName", "John") ;
m.get("isDirty") ; // --> true

Now, I don't know how to save, things like

m.save() ;
App.MyModel.save(m) ;
//etc

do not work. Any suggestions ?

CHeers

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333

2 Answers2

51

The accepted answer is no longer valid since the release of Ember Data 1.0 (beta at the time of writing). Saving is much easier and more intuitive with Ember Data (1.0).

var person = this.store.createRecord('person');
person.set('frist_name', 'John');
person.set('last_name', 'Doe');
person.save();

It is also good to know that a save call returns a promise, which is resolved when the server returns a response.

person.save().then(function() {
  // SUCCESS
}, function() {
  // FAILURE
});
Bart Jacobs
  • 9,022
  • 7
  • 47
  • 88
1

EDIT: This is now out of date with Ember Data 1.0 beta and onwards, please refer to Bart's answer

If you are using Ember-Data, you need to call commit() on the model's transaction.

m.get('transaction').commit()

or if you want to save every dirty object in your app

m.get('store').commit()
Bradley Priest
  • 7,438
  • 1
  • 29
  • 33
  • there is still one weird thing, if I create a new model and try to save it like: var p = App.Post.createRecord({firstName: "bla", lastName: "blabla"}); p.get("transaction").commit(); The request that this call creates is a GET to http://localhost/~ME/posts/ – Jeanluca Scaljeri Jan 22 '13 at 16:57
  • 1
    That's really weird, have you customized the adapter at all? It should really be a POST request to `/posts` – Bradley Priest Jan 23 '13 at 03:02
  • yep, I've extended the RESTAdapter, because I had to set the 'namespace': App.Adapter = DS.RESTAdapter.extend({namespace: '~User123'}); Is there something that can be done to fix this, and if so, is this somewhere documented ? – Jeanluca Scaljeri Jan 23 '13 at 12:08
  • No, you would have had to do some serious rewriting of the adapter to get your POST requests sent as GET requests, are you sure you don't have some middleware or something that might be converting them? – Bradley Priest Jan 24 '13 at 03:40
  • My mistake, I do see the POST now, for some reason it didn't show up in my console, only the GET which is done after the POST. So the commit() does a POST and then a GET, why ? – Jeanluca Scaljeri Jan 25 '13 at 12:51