如何克隆Ember数据记录,包括关系?

Ker*_*ick 7 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));
Run Code Online (Sandbox Code Playgroud)

mac*_*acu 8

Daniel的答案的一些改进,允许提供覆盖,并清除新记录的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);
    }
});
Run Code Online (Sandbox Code Playgroud)


小智 4

这是我使用的克隆函数。照顾所属协会。

 DS.Model.reopen({
   clone: function() {
    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)
      }
    })

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

})
Run Code Online (Sandbox Code Playgroud)