我想要克隆当前正在编辑的模型.
我找到了几种几乎可以工作的方法.但两者都不完美.
1)model.get('data.attributes')获取除camelCase形式的关系之外的所有属性,生成新的记录,但当然缺少关系.
2)model.serialize()生成一个JSON对象,其中包含所有属性,包括关系.但createRecord由于对象不是camelCased(具有下划线的属性first_name不会被处理),因此无法很好地处理它
创建克隆后,我想transaction.createRecord(App.Document, myNewModelObject)更改/设置几个属性,最后commit().任何人都有一些如何做到这一点的见解?
现在我们有一个复制模型ember-cli-copyable的附加组件
使用此添加,只需将Copyable混合添加到要复制的目标模型并使用复制方法
来自附加站点的示例
import Copyable from 'ember-cli-copyable';
Account = DS.Model.extend( Copyable, {
name: DS.attr('string'),
playlists: DS.hasMany('playList'),
favoriteSong: DS.belongsTo('song')
});
PlayList = DS.Model.extend( Copyable, {
name: DS.attr('string'),
songs: DS.hasMany('song'),
});
//notice how Song does not extend Copyable
Song = DS.Model.extend({
name: DS.attr('string'),
artist: DS.belongsTo('artist'),
});
//now the model can be copied as below
this.get('currentAccount.id') // => 1
this.get('currentAccount.name') // => 'lazybensch'
this.get('currentAccount.playlists.length') // => 5
this.get('currentAccount.playlists.firstObject.id') // => 1
this.get('currentAccount.favoriteSong.id') // => 1
this.get('currentAccount').copy().then(function(copy) {
copy.get('id') // => 2 (differs from currentAccount)
copy.get('name') // => 'lazybensch'
copy.get('playlists.length') // => 5
copy.get('playlists.firstObject.id') // => 6 (differs from currentAccount)
copy.get('favoriteSong.id') // => 1 (the same object as in currentAccount.favoriteSong)
});
Run Code Online (Sandbox Code Playgroud)
kro*_*ofy -1
这是更新的答案,它仍然不处理hasMany关系。
cloneBelongsTo: function(fromModel, toModel) {
var relationships;
relationships = Em.get(fromModel.constructor, 'relationships');
return relationships.forEach(function(relationshipType) {
var _relType;
_relType = relationships.get(relationshipType);
return _relType.forEach(function(relationship) {
var name, relModel;
relModel = Em.get(fromModel, relationship.name);
if (relationship.kind === 'belongsTo' && relModel !== null) {
name = relationship.name;
return toModel.set(name, fromModel.get(name));
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
我的使用方法如下:
// create a JSON representation of the old model
var newModel = oldModel.toJSON();
// set the properties you want to alter
newModel.public = false;
// create a new record
newDocument = store.createRecord('document', newModel);
// call the cloneBelongsTo method after the record is created
cloneBelongsTo(model, newDocument);
// finally save the new model
newDocument.save();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8947 次 |
| 最近记录: |