如何保存记录及其模型关系

How to save a record and its model relationships

在博客应用程序中,用户编写 post 并为其选择一些标签。当用户单击“发布”时,它会执行 publishPost 操作,当前会执行以下操作,但显然不正确,因为 post 保存时,标签不会。虽然控制台中没有抛出错误:

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 并在后端执行了 SELECT(不是 INSERT)语句(Rails w/JSONAPI)。有什么想法吗?

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 
  });
}