【问题标题】:Ember, Ember Data - Updating hasMany relationEmber,Ember 数据 - 更新 hasMany 关系
【发布时间】:2015-11-17 06:42:26
【问题描述】:

我正在尝试更新 Ember 中的 hasMany 关系,但在正确发送数据时遇到了一些问题。

我有以下 Ember 模型:

// models/post.js
export default DS.Model.extend({
    title: DS.attr('string'),
    tags: DS.hasMany('tag', { async: true })
});

// models/tag.js
export default DS.Model.extend({
    title: DS.attr('string'),
    post: DS.belongsTo('post', { async: true })
});

然后我在路由中执行以下操作来创建新标签并更新帖子:

addTag: function() {
    var post = this.get('currentModel');

    var newTag = this.store.createRecord('tag', {
        title: 'Lorem Ipsum',
        post: post
    });

    newTag.save().then(function() {
        post.get('tags').pushObject(newTag);

        post.save();
    });
}

新标签已成功创建并由我的 Express api 保存,但帖子未正确保存。它由 api 接收,但 Ember 发出的请求负载从不包含标签 ID(尽管它确实发送标签标题)。我究竟做错了什么?非常感谢任何帮助!


编辑

事实证明,默认情况下 RESTSerializer 不会序列化并包含 hasMany 关系的相关 ID。它只将它们包含在 belongsTo 端,因为它希望 API 负责在需要的地方保存它。我可能会更改我的 API 以适应这种行为,因为它更有效,但如果其他人遇到这种情况,可以通过扩展序列化程序并使用 DS.EmbeddedRecordsMixin mixin - http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html - 使序列化程序包含 ID看起来像这样:

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        tags: { serialize: 'ids' }
    }
});

【问题讨论】:

    标签: ember-data


    【解决方案1】:

    您无需在发布时调用 .save()。当您调用 createRecord 创建标签时,您的后端会收到 post 的 id 并应相应地保持依赖关系。

    addTag: function() {
        var post = this.get('currentModel');
    
        this.store.createRecord('tag', {
              title: 'Lorem Ipsum',
              post: post})
           .save()
           .then(function(tag) {
              post.get('tags').pushObject(tag);
           });
    

    【讨论】:

      【解决方案2】:

      遇到同样的问题。

      目前我通过serializeHasMany钩子解决。

      // app/serializers/application
      import {ActiveModelSerializer} from 'active-model-adapter';
      
      export default ActiveModelSerializer.extend({
        serializeHasMany: function(snapshot, json, relationship){
          this._super.apply this, arguments
          if (!json[relationship.type + '_ids']){
            var ids = []
            snapshot.record.get(relationship.key).forEach(function(item){
              ids.push item.get 'id'
            });
            json[relationship.type + '_ids'] = ids
          }
        }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-05
        • 2016-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-29
        • 2016-07-24
        相关资源
        最近更新 更多