7.3 Models -- Creating And Deleting Records

一、Creating

1. 你可以通过调用在store中的createRecord方法来创建records。

store.createRecord('post', {
  title: 'Rails is Omakase',
  body: 'Lorem ipsum'
});

2. 这个store对象可以通过this.storecontrollersroutes中使用。

3. 尽管createRecord相当简单,唯一要注意的是你不能分配一个promise作为一个关系。例如,如果你希望设置一个postauthor属性,如果user的id没有被加载进store,这将不会实现:

var store = this.store;

store.createRecord('post', {
  title: 'Rails is Omakase',
  body: 'Lorem ipsum',
  author: store.findRecord('user', 1)
});

4. 然而,在这个promise实现之后你可以很容易的设置关系:

var store = this.store;

var post = store.createRecord('post', {
  title: 'Rails is Omakase',
  body: 'Lorem ipsum'
});

store.findRecord('user', 1).then(function(user) {
  post.set('author', user);
});

二、Deleting records

删除记录和创建记录一样简单。仅仅是调用 DS.Model任意实例上的deleteRecord()方法。这标记这个record是isDeleted并且因此从store上的all()查询上移除它。

然后使用save()删除可以被持久化(指在数据库上也删除)。或者,你可以使用destroyRecord方法同事删除并持久化。

store.findRecord('post', 1).then(function(post) {
  post.deleteRecord();
  post.get('isDeleted'); // => true
  post.save(); // => DELETE to /posts/1
});

// OR
store.findRecord('post', 2).then(function(post) {
  post.destroyRecord(); // => DELETE to /posts/2
});
原文地址:https://www.cnblogs.com/sunshineground/p/5165950.html