Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember clone model for new record

Tags:

ember.js

I want to make a clone of a model currently being edited.

I've found a couple of ways that almost work. But neither are perfect.

1) model.get('data.attributes') gets all the attributes except for relationships in camelCase form, generates a new record fine but the relationships are missing of course.

2) model.serialize() generates a JSON object, with all attributes including relationships. But createRecord will not handle it well since the object is not camelCased (attributes with underscores like first_name will not be handled)

After my clone has been created I want to transaction.createRecord(App.Document, myNewModelObject) change/set a couple of attributes and finally commit(). Anyone have some insight in how to do this?

like image 463
kroofy Avatar asked Feb 16 '13 16:02

kroofy


1 Answers

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) 

});
like image 56
Vinoth Kumar Avatar answered Sep 29 '22 02:09

Vinoth Kumar