Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Ember Creates, updates, and deletes records


May 09, 2021 Ember.js Reference documents


Table of contents


The previous article introduced the query method, this article introduces the new, updated, delete the record method. T he sample code for this article was created on the basis of the previous article. For consolidating firebase, route template and templates, see the last article to add a controller: ember g controller articles

1, create a new record

Create a new record createRecord() method. F or example, the following code creates aritcle record. Modify the template and add a few input to the template to enter article information.

  1. <div class="container">
  2. <div class="row">
  3. <div class="col-md-4 col-xs-4">
  4. <ul class="list-group">
  5. {{#each model as |item|}}
  6. <li class="list-group-item">
  7. {{#link-to 'articles.article' item.id}}
  8. {{item.title}} -- <small>{{item.category}}</small>
  9. {{/link-to}}
  10. </li>
  11. {{/each}}
  12. </ul>
  13. <div>
  14. title:{{input value=title}}<br>
  15. body: {{textarea value=body cols="80" rows="3"}}<br>
  16. category: {{input value=category}}<br>
  17. <button {{ action "saveItem"}}>保存</button>
  18. <font color='red'>{{tipInfo}}</font>
  19. </div>
  20. </div>
  21. <div class="col-md-8 col-xs-8">
  22. {{outlet}}
  23. </div>
  24. </div>
  25. </div>

The fields of the page correspond to the properties of this model article C lick "Save" and submit to controller Here's the controller that gets the data to controller

  1. // app/controllers/articles.js
  2. import Ember from 'ember';
  3. export default Ember.Controller.extend({
  4. actions: {
  5. // 表单提交,保存数据到Store。Store会自动更新到firebase
  6. saveItem: function() {
  7. var title = this.get('title');
  8. if ('undefined' === typeof(title) || '' === title.trim()) {
  9. this.set('tipInfo', "title不能为空");
  10. return ;
  11. }
  12. var body = this.get('body');
  13. if ('undefined' === typeof(body) || '' === body.trim()) {
  14. this.set('tipInfo', "body不能为空");
  15. return ;
  16. }
  17. var category = this.get('category');
  18. if ('undefined' === typeof(category) || '' === category.trim()) {
  19. this.set('tipInfo', "category不能为空");
  20. return ;
  21. }
  22. // 创建数据记录
  23. var article = this.store.createRecord('article', {
  24. title: title,
  25. body: body,
  26. category: category,
  27. timestamp: new Date().getTime()
  28. });
  29. article.save(); //保存数据的到Store
  30. // 清空页面的input输入框
  31. this.set('title', "");
  32. this.set('body', "");
  33. this.set('category', "");
  34. }
  35. }
  36. });

The first argument is the model name, which focuses on the createRecord method. T he second argument is a hash, in which the model property value is always set. F inally, article.save() method is called to save the data to the Store and then Store to firebase. Here's how it works:

Ember Creates, updates, and deletes records

Enter the information and the data will appear immediately after the list "no form--java" when you click "Save". You can then click on the title to query the details, and the body's information will appear at the back of the page.

Through the example here I think you should know createRecord() method! B ut what if there are two models that are associated with the method of saving? A new model is added below.

  1. ember g model users

Then add an association to the model.

  1. // app/models/article.js
  2. import DS from 'ember-data';
  3. export default DS.Model.extend({
  4. title: DS.attr('string'),
  5. body: DS.attr('string'),
  6. timestamp: DS.attr('number'),
  7. category: DS.attr('string'),
  8. author: DS.belongsTo('user') //关联user
  9. });
  10. // app/models/user.js
  11. import DS from 'ember-data';
  12. export default DS.Model.extend({
  13. username: DS.attr('string'),
  14. timestamp: DS.attr('number'),
  15. articles: DS.hasMany('article') //关联article
  16. });

Modifying articles.hbs adds an input author information field to the interface.

  1. ……省略其他代码
  2. <div>
  3. title:{{input value=title}}<br>
  4. body: {{textarea value=body cols="80" rows="3"}}<br>
  5. category: {{input value=category}}<br>
  6. <br>
  7. author: {{input value=username}}<br>
  8. <button {{ action "saveItem"}}>保存</button>
  9. <font color='red'>{{tipInfo}}</font>
  10. </div>
  11. ……省略其他代码

Here's a look at how to set the correlation between the two models in controller There are two ways to set up, one createRecord() method and the other outside the method.

  1. // app/controllers/articles.js
  2. import Ember from 'ember';
  3. export default Ember.Controller.extend({
  4. actions: {
  5. // 表单提交,保存数据到Store。Store会自动更新到firebase
  6. saveItem: function() {
  7. // 获取信息和校验代码省略……
  8. // 创建user
  9. var user = this.store.createRecord('user', {
  10. username: username,
  11. timestamp: new Date().getTime()
  12. });
  13. // 必须要执行这句代码,否则user数据不能保存到Store,
  14. // 否则article通过user的id查找不到user
  15. user.save();
  16. // 创建article
  17. var article = this.store.createRecord('article', {
  18. title: title,
  19. body: body,
  20. category: category,
  21. timestamp: new Date().getTime(),
  22. author: user //设置关联
  23. });
  24. article.save(); //保存数据的到Store
  25. // 清空页面的input输入框
  26. this.set('title', "");
  27. this.set('body', "");
  28. this.set('category', "");
  29. this.set('username', "");
  30. }
  31. }
  32. });

Ember Creates, updates, and deletes records

Enter the information shown above, and click "Save" to see the following data association in the background of firebase.

Ember Creates, updates, and deletes records

Note: The association with these two data is maintained by id the data. So what if I want to user information through article

Get both directly in an object-oriented manner.

  1. {{#each model as |item|}}
  2. <li class="list-group-item">
  3. {{#link-to 'articles.article' item.id}}
  4. {{item.title}} -- <small>{{item.category}}</small> -- <small>{{item.author.username}}</small>
  5. {{/link-to}}
  6. </li>
  7. {{/each}}

Watch out for {{ item.author.username }} M uch like EL expression!! T he association between the two models was mentioned earlier in two ways. The following code is the second way:

  1. // 其他代码省略……
  2. // 创建article
  3. var article = this.store.createRecord('article', {
  4. title: title,
  5. body: body,
  6. category: category,
  7. timestamp: new Date().getTime()
  8. // ,
  9. // author: user //设置关联
  10. });
  11. // 第二种设置关联关系方法,在外部手动调用set方法设置
  12. article.set('author', user);
  13. // 其他代码省略……

Run, re-enter the information, and the results are consistent. Y ou can even call the createRecord method to set the relationship between the two models. For example, the following snipp is a snipper:

  1. var store = this.store; // 由于作用域问题,在createRecord方法内部不能使用this.store
  2. var article = this.store.createRecord('article', {
  3. title: title,
  4. // ……
  5. // ,
  6. // author: store.findRecord('user', 1) //设置关联
  7. });
  8. // 第二种设置关联关系方法,在外部手动调用set方法设置
  9. article.set('author', store.findRecord('user', 1));

This way, you can get the record directly and dynamically based on the user's id property value, and then set the association. The new introduction is over, followed by the update of the record.

2, update the record

Updates are very similar to new ones. Take a look at the following snippppy code: First add the updated settings code to the template and modify the articles/article.hbs

  1. <h1>{{model.title}}</h1>
  2. <div class = "body">
  3. {{model.body}}
  4. </div>
  5. <div>
  6. <br><hr>
  7. 更新测试<br>
  8. title: {{input value=model.title}}<br>
  9. body:<br> {{textarea value=model.body cols="80" rows="3"}}<br>
  10. <button {{action 'updateArticleById' model.id}}>更新文章信息</button>
  11. </div>

Add a controller, controller handles the modification information submitted by the sub-template.

  1. ember g controller articles/article
  1. // app/controllers/articles/article.js
  2. import Ember from 'ember';
  3. export default Ember.Controller.extend({
  4. actions: {
  5. // 根据文章id更新
  6. updateArticleById: function(params) {
  7. var title = this.get('model.title');
  8. var body = this.get('model.body');
  9. this.store.findRecord('article', params).then(function(art) {
  10. art.set('title', title);
  11. art.set('body', body);
  12. // 保存更新的值到Store
  13. art.save();
  14. });
  15. }
  16. }
  17. });

Select the data that needs to be updated on the left, and then modify the data that needs to be updated in the input box on the right, and during the modification process you can see that the modified information will immediately be reflected on the interface, because Ember automatically updates the data in the Store (remember the observer you said a long time ago?). )。

Ember Creates, updates, and deletes records

If you don't click Update Article Information to submit, the information you modify won't be updated to firebase. The page refreshes as it is, and if you click update article information data, the updated information will be submitted to firebase.

Because save findRecord method returns a value that promises object, you can also handle error situations. For example, the following code:

  1. var user = this.store.createRecord('user', {
  2. // ……
  3. });
  4. user.save().then(function(fulfill) {
  5. // 保存成功
  6. }).catch(function(error) {
  7. // 保存失败
  8. });
  9. this.store.findRecord('article', params).then(function(art) {
  10. // ……
  11. }).catch(function(error) {
  12. // 出错处理代码
  13. });

Specific code I will not demonstrate, please readers write their own tests! !

3, delete the record

Now that there is a new addition then there will usually be deletion. The deletion of records is very similar to modification, which is to query out the data to be deleted first, and then perform the deletion.

  1. // app/controllers/articles.js
  2. import Ember from 'ember';
  3. export default Ember.Controller.extend({
  4. actions: {
  5. // 表单提交,保存数据到Store。Store会自动更新到firebase
  6. saveItem: function() {
  7. // 省略
  8. },
  9. // 根据id属性值删除数据
  10. delById : function(params) {
  11. // 任意获取一个作为判断表单输入值
  12. if (params && confirm("你确定要删除这条数据吗??")) {
  13. // 执行删除
  14. this.store.findRecord('article', params).then(function(art) {
  15. art.destroyRecord();
  16. alert('删除成功!');
  17. }, function(error) {
  18. alert('删除失败!');
  19. });
  20. } else {
  21. return;
  22. }
  23. }
  24. }
  25. });

Modify the template that displays the data, add the delete button, and pass the id data to controller

  1. <div class="container">
  2. <div class="row">
  3. <div class="col-md-4 col-xs-4">
  4. <ul class="list-group">
  5. {{#each model as |item|}}
  6. <li class="list-group-item">
  7. {{#link-to 'articles.article' item.id}}
  8. {{item.title}} -- <small>{{item.category}}</small> -- <small>{{item.author.username}}</small>
  9. {{/link-to}}
  10. <button {{action 'delById' item.id}}>删除</button>
  11. </li>
  12. {{/each}}
  13. </ul>
  14. // ……省略其他代码
  15. </div>
  16. </div>

Ember Creates, updates, and deletes records

As shown above, click on the second data deletion button. P op-up prompt window, click "OK" after the successful deletion of data, and pop up "Delete successfully!" " , looking at the data in the firebase background, has indeed been deleted successfully. H owever, the user associated with this is not deleted, and under normal circumstances the associated user data should not be deleted. The end result is only one data:

Ember Creates, updates, and deletes records

At this end, the new, updated, delete methods are introduced. D etailed demo examples have been given, and I believe that if you have personally practiced them in your own projects, it is easy to master these methods!
The full code of the blog post is placed in Github (the blog post has been modified several times, and the code on the blog post may be different from the github code, but the impact is small!). I f you think the blog post is a bit useful to you, please give me a star on the star project. Yours is definitely the biggest motivation for me!!