How can I clone an Ember Data record, including relationships?

后端 未结 4 1179
我在风中等你
我在风中等你 2021-02-09 04:45

I\'ve figured out that I can clone an Ember Data record and copy its Attributes, but none of the belongsTo/hasMany relationships are cloned. Can I do t

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-09 05:39

    Here is a clone function that I use. Takes care of the belongs to associations.

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

提交回复
热议问题