You can create records by calling the createRecord method on the store.

通过调用仓库的createRecord方法,可以创建记录:

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

The store object is available in controllers and routes using this.store.

仓库对象在控制器和路由中都可以通过this.store来访问。

Although createRecord is fairly straightforward, the only thing to watch out for is that you cannot assign a promise as a relationship, currently.

尽管createRecord的使用已经非常直接,但是还需要注意一点,就是目前还不支持将一个承诺赋值给一个关联。

For example, if you want to set the author property of a post, this would not work if the user with id isn’t already loaded into the store:

例如,如果希望给文章设置author属性,如果指定ID的user并没有加载到仓库中的话,下面的代码将不会正常工作。

  1. var store = this.store;
  2. store.createRecord('post', {
  3. title: 'Rails is Omakase',
  4. body: 'Lorem ipsum',
  5. author: store.find('user', 1)
  6. });

However, you can easily set the relationship after the promise has fulfilled:

不过在承诺履行时可以非常方便的进行关联关系的设置:

  1. var store = this.store;
  2. var post = store.createRecord('post', {
  3. title: 'Rails is Omakase',
  4. body: 'Lorem ipsum'
  5. });
  6. store.find('user', 1).then(function(user) {
  7. post.set('author', user);
  8. });

Deleting Records

删除记录

Deleting records is just as straightforward as creating records. Just call deleteRecord() on any instance of DS.Model. This flags the record as isDeleted and thus removes it from all() queries on the store. The deletion can then be persisted using save(). Alternatively, you can use the destroyRecord method to delete and persist at the same time.

删除记录与创建记录一样简单。只需要调用DS.Model实例的deleteRecord()方法即可。这将会吧记录标记为isDeleted,并且不在storeall()查询中返回。删除操作之后会通过使用save()来进行持久化。此外,也可以使用destroyRecord来将删除和持久化一次完成。

  1. var post = store.find('post', 1);
  2. post.deleteRecord();
  3. post.get('isDeleted'); // => true
  4. post.save(); // => DELETE to /posts/1
  5. // OR
  6. var post = store.find('post', 2);
  7. post.destroyRecord(); // => DELETE to /posts/2