Ember clone model for new record

How about using toJSON() method instead of serialize() like this

js transaction.createRecord(App.Document, model.toJSON());


Now we have a add-on to copy models ember-cli-copyable

With this add on, just add the Copyable mix-in to the target model which is to be copied and use the copy method

Example from the add-on site

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) 

});

Tags:

Ember.Js