在博客应用程序中,用户写一篇文章并为其选择一些标签。当用户单击发布时,它执行当前执行publishPost
以下操作但显然不对的操作,因为在保存帖子时,标签没有。但是控制台中没有抛出错误:
actions: {
publishPost: function() {
var post = this.store.createRecord('post', {
title: this.get('title'),
body: this.get('body')
});
post.set('tags', this.get('newTags')); // array of tag model objects (post hasMany tags in the model file)
post.save();
}
}
我也试过直接添加tags: this.get('newTags')
到“post”对象中:
actions: {
publishPost: function() {
var post = this.store.createRecord('post', {
title: this.get('title'),
body: this.get('body'),
tags: this.get('newTags')
});
post.save();
}
}
这在 Ember 中通常是如何处理的?
**** 更新 ****
@Jeff 我实现了你的建议,但由于某种原因,它启动了一个 PATCH 并在后端(带有 JSONAPI 的 Rails)上执行了一个 SELECT(而不是 INSERT)语句。有任何想法吗?
Started POST "/posts" for ::1 at 2018-02-26 22:21:43 -0800
Processing by PostsController#create as API_JSON
Parameters: {"data"=>{"attributes"=>{"title"=>"asdfg", "body"=>"gfdsa", "created-at"=>nil, "updated-at"=>nil}, "type"=>"posts"}}
(0.2ms) BEGIN
SQL (0.3ms) INSERT INTO `posts` (`title`, `body`, `created_at`, `updated_at`) VALUES ('asdfg', 'gfdsa', '2018-02-27 06:21:43', '2018-02-27 06:21:43')
(1.1ms) COMMIT
Rendering text template
Rendered text template (0.0ms)
Completed 201 Created in 9ms (Views: 0.6ms | ActiveRecord: 1.6ms)
Started PATCH "/tags/18" for ::1 at 2018-02-26 22:21:43 -0800
Started PATCH "/tags/53" for ::1 at 2018-02-26 22:21:43 -0800
Processing by TagsController#update as API_JSON
Processing by TagsController#update as API_JSON
Parameters: {"data"=>{"id"=>"18", "attributes"=>{"name"=>"A.I."}, "type"=>"tags"}, "id"=>"18"}
Parameters: {"data"=>{"id"=>"53", "attributes"=>{"name"=>"bigfoot"}, "type"=>"tags"}, "id"=>"53"}
(1.7ms) BEGIN
(0.3ms) BEGIN
Tag Load (1.1ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`id` = 18 ORDER BY `tags`.`id` ASC LIMIT 1
Tag Load (0.3ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`id` = 53 ORDER BY `tags`.`id` ASC LIMIT 1
(1.3ms) COMMIT
(0.3ms) COMMIT
Rendering text template
Rendering text template
Rendered text template (0.0ms)
Rendered text template (0.0ms)
Completed 200 OK in 12ms (Views: 1.6ms | ActiveRecord: 4.1ms)
Completed 200 OK in 10ms (Views: 0.9ms | ActiveRecord: 0.9ms)
以下是我的做法(使用 RESTApi)。
它可能不是最好的或唯一的解决方案,它甚至可能与 JSONApi 不同。
publishPost: function() {
var post = this.store.createRecord('post', {
title: this.get('title'),
body: this.get('body')
});
post.save().then(post => {
let tags = this.get('tags');
// loop through your tags here
let newTag = {
foo: 'bar',
post: post
};
let tag = this.store.createRecord('tag', newTag);
tag.save();
// end of loop
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句