Last active
August 29, 2015 14:03
-
-
Save macu/c11b11d67a7f9b36259a to your computer and use it in GitHub Desktop.
Reopen the Model class, to allow cloning records with overrides.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Ember from 'ember'; | |
| import DS from 'ember-data'; | |
| /** | |
| * Returns the model class name, dasherized, which can be used to find | |
| * and create new models of the same type through the store. | |
| */ | |
| export function getClassName(model) { | |
| // typeKey introduced in Ember Data 1.0.0.beta.3 | |
| var typeKey = model.constructor.typeKey; | |
| return Ember.String.dasherize(typeKey); | |
| } | |
| export function initialize() { | |
| // Thanks http://stackoverflow.com/a/22514312 | |
| DS.Model.reopen({ | |
| clone: function(overrides) { | |
| var model = this, attrs = model.toJSON(); | |
| var root = getClassName(model); | |
| /* | |
| * 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); | |
| }, | |
| }); | |
| }; | |
| export default { | |
| name: 'model-cloning', | |
| initialize: initialize | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment