ember.js - 如何克隆 Ember 数据记录,包括关系?

标签 ember.js ember-data

我发现我可以克隆 Ember 数据记录并复制其属性,但没有任何 belongsTo/hasMany 关系被克隆。如果我不知道可能存在什么关系,脱离现有的关系,我可以以某种方式做到这一点吗?

作为引用,以下是我将克隆 Ember 数据记录属性的内容:

var attributeKeys = oldModel.get('constructor.attributes.keys.list');
var newRecord = this.get('store').createRecord(oldModel.constructor.typeKey);
newRecord.setProperties(oldModel.getProperties(attributeKeys));

最佳答案

对 Daniel 的 answer 进行了一些改进为了安全起见,它允许提供覆盖并清除新记录的 ID。另外,我不喜欢在克隆方法中调用 save ,而是将其留给调用者。

DS.Model.reopen({
    clone: function(overrides) {
        var model = this,
            attrs = model.toJSON(),
            class_type = model.constructor;

        var root = Ember.String.decamelize(class_type.toString().split('.')[1]);

        /*
         * Need to replace the belongsTo association ( id ) with the
         * actual model instance.
         *
         * For example if belongsTo association is project, the
         * json value for project will be:  ( project: "project_id_1" )
         * and this needs to be converted to ( project: [projectInstance] )
         */
        this.eachRelationship(function(key, relationship) {
            if (relationship.kind == 'belongsTo') {
                attrs[key] = model.get(key);
            }
        });

        /*
         * Need to dissociate the new record from the old.
         */
        delete attrs.id;

        /*
         * Apply overrides if provided.
         */
        if (Ember.typeOf(overrides) === 'object') {
            Ember.setProperties(attrs, overrides);
        }

        return this.store.createRecord(root, attrs);
    }
});

关于ember.js - 如何克隆 Ember 数据记录,包括关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20007049/

相关文章:

javascript - Ember.js 2.4 中的更新记录

javascript - Ember 更新视频源但未被浏览器反射(reflect)

json - 删除 Ember 数据中 POST/PUT 操作的 JSON 根元素

javascript - 为 Handlebars 模板中的模型赋值

javascript - Mocha 通过了应该失败的测试 (ember-mocha-adapter)

json - Ember 数据和映射 JSON 对象

javascript - 嵌套 promise 并在 route 返回它们不会更新路线模型和使用该模型的模板

ember.js - 如何将多个参数传递给 Ember2.3 中 select 元素的 onChange 操作

javascript - 如何存储从 JSON 过滤的数据并在表中显示 (EmberJS)

javascript - 我们如何使用 ember-cli 对模型混合进行单元测试