在将 ember-data 从 2.13 提升到 2.14 之后,当关系模型具有空关系时,请求负载不包含 hasMany 关系

After bump ember-data from 2.13 to 2.14 the request payload not contain hasMany relations when the relation model had empty relation

with ActiveModelSerializer 在 ember-data 升级后,当模型没有 record by relation 时,请求负载上 has_many case 的值发生了变化,例如:

// app/models/user.js
import Model from 'ember-data/model';
import { hasMany } from 'ember-data/relationships';

export default Model.extend(Validations, {
  posts: hasMany('post'),
...
}
// app/models/post.js
import Model from 'ember-data/model';
import { belongsTo } from 'ember-data/relationships';

export default Model.extend(Validations, {
  user: belongsTo('user'),
...
}

所以,如果用户没有帖子,之前被发送 [] 到 BE,但在 ember-data 撞到 2.14.11 之后没有发送键值,例如:(请求负载)

之前:

user: { id: 1, post_ids: [] }

之后:

user: { id: 1 }

注:

"active-model-adapter": "2.2.0"
"ember-data": "2.14.11"

原因是:https://github.com/emberjs/data/compare/v2.14.3...v2.14.4

解决方法:app/serializers/application.js

import EmbeddedRecordsMixin from 'ember-data/serializers/embedded-records-mixin';
import { ActiveModelSerializer } from 'active-model-adapter';
import { pluralize } from 'ember-inflector';

export default ActiveModelSerializer.extend(EmbeddedRecordsMixin, {
  isNewSerializerAPI: true,

  serializeHasMany(snapshot, model, relation) {
    this._super(...arguments);
    let relationKey = `${pluralize(relation.key.underscore()).slice(0, -1)}_ids`;
    if (relation.kind === 'hasMany' && !model[relationKey]) {
      model[relationKey] = Object.freeze([]);
    }
  }
});