Ember clone model for new record












15














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?










share|improve this question



























    15














    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?










    share|improve this question

























      15












      15








      15


      1





      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?










      share|improve this question













      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?







      ember.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Feb 16 '13 at 16:23









      kroofy

      7961621




      7961621
























          6 Answers
          6






          active

          oldest

          votes


















          5














          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)

          });





          share|improve this answer





























            1














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



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






            share|improve this answer





















            • toJSON() cannot be used if there are relationships, which is a quite common requirement.
              – iOS dev
              Jun 1 at 22:38



















            0














            Here's an updated answer, it still doesn't handle hasMany relationships.



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


            And here's how I use it:



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





            share|improve this answer























            • I have now an example of adding belongsTo items also: stackoverflow.com/q/20477301/1153884
              – DelphiLynx
              Dec 16 '13 at 10:30










            • Did you figure out how to do hasMany? I ended up doing this which seems to work, but it probably isn't the best way. this.eachRelationship(function(key, relationship){ self._data[key].forEach(function(obj) { newRecord.get(key).addObject(obj); }) });
              – Cameron Ketcham
              May 28 '14 at 6:59





















            0














            Most simple way I found:



            function cloneModel(model) {
            const root = model._internalModel.modelName;
            const store = model.get('store');
            let attrs = model.toJSON();

            attrs.id = `clone-${attrs.id}`;
            store.pushPayload({
            [root]: attrs
            });
            return store.peekRecord(root, attrs.id);
            }





            share|improve this answer





























              0














              Here is the simple way to clone your Ember Model with relationships. working fine.



              Create a Copyable mixin like,



              import Ember from 'ember';

              export default Ember.Mixin.create(Ember.Copyable, {

              copy(deepClone) {
              var model = this, attrs = model.toJSON(), class_type = model.constructor;
              var root = Ember.String.decamelize(class_type.toString().split(':')[1]);

              if(deepClone) {
              this.eachRelationship(function(key, relationship){
              if (relationship.kind == 'belongsTo') {
              attrs[key] = model.get(key).copy(true);
              } else if(relationship.kind == 'hasMany' && Ember.isArray(attrs[key])) {
              attrs[key].splice(0);
              model.get(key).forEach(function(obj) {
              attrs[key].addObject(obj.copy(true));
              });
              }
              });
              }
              return this.store.createRecord(root, attrs);
              }
              });


              Add the mixin in your model,



              Note: If you want to clone your child model then, you need to include the mixin in child model as well



              USAGE:




              1. With relationship : YOURMODEL.copy(true)

              2. Without relationship : YOURMODEL.copy()






              share|improve this answer





























                0














                This will also solve my problem



                Account = DS.Model.extend({
                name: DS.attr('string'),
                playlists: DS.hasMany('playList'),
                favoriteSong: DS.belongsTo('song')
                });

                Duplicate = Ember.Object.extend({});

                TemporaryRoute = Ember.Route.extend({
                model : function(){
                var model = this.store.findAll('account');
                var json = model.toJSON();
                var duplicateModel = Duplicate.create(json);
                this.set('duplicateModel', duplicateModel);
                return model;
                }
                });





                share|improve this answer























                • findAll returns Promise. so you can't do model.toJSON immediately.
                  – Ember Freak
                  Jun 28 '17 at 7:35













                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14912425%2fember-clone-model-for-new-record%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                6 Answers
                6






                active

                oldest

                votes








                6 Answers
                6






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                5














                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)

                });





                share|improve this answer


























                  5














                  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)

                  });





                  share|improve this answer
























                    5












                    5








                    5






                    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)

                    });





                    share|improve this answer












                    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)

                    });






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Sep 11 '15 at 7:52









                    Vinoth Kumar

                    87711020




                    87711020

























                        1














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



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






                        share|improve this answer





















                        • toJSON() cannot be used if there are relationships, which is a quite common requirement.
                          – iOS dev
                          Jun 1 at 22:38
















                        1














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



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






                        share|improve this answer





















                        • toJSON() cannot be used if there are relationships, which is a quite common requirement.
                          – iOS dev
                          Jun 1 at 22:38














                        1












                        1








                        1






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



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






                        share|improve this answer












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



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







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Aug 27 '13 at 14:31









                        user2007804

                        273




                        273












                        • toJSON() cannot be used if there are relationships, which is a quite common requirement.
                          – iOS dev
                          Jun 1 at 22:38


















                        • toJSON() cannot be used if there are relationships, which is a quite common requirement.
                          – iOS dev
                          Jun 1 at 22:38
















                        toJSON() cannot be used if there are relationships, which is a quite common requirement.
                        – iOS dev
                        Jun 1 at 22:38




                        toJSON() cannot be used if there are relationships, which is a quite common requirement.
                        – iOS dev
                        Jun 1 at 22:38











                        0














                        Here's an updated answer, it still doesn't handle hasMany relationships.



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


                        And here's how I use it:



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





                        share|improve this answer























                        • I have now an example of adding belongsTo items also: stackoverflow.com/q/20477301/1153884
                          – DelphiLynx
                          Dec 16 '13 at 10:30










                        • Did you figure out how to do hasMany? I ended up doing this which seems to work, but it probably isn't the best way. this.eachRelationship(function(key, relationship){ self._data[key].forEach(function(obj) { newRecord.get(key).addObject(obj); }) });
                          – Cameron Ketcham
                          May 28 '14 at 6:59


















                        0














                        Here's an updated answer, it still doesn't handle hasMany relationships.



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


                        And here's how I use it:



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





                        share|improve this answer























                        • I have now an example of adding belongsTo items also: stackoverflow.com/q/20477301/1153884
                          – DelphiLynx
                          Dec 16 '13 at 10:30










                        • Did you figure out how to do hasMany? I ended up doing this which seems to work, but it probably isn't the best way. this.eachRelationship(function(key, relationship){ self._data[key].forEach(function(obj) { newRecord.get(key).addObject(obj); }) });
                          – Cameron Ketcham
                          May 28 '14 at 6:59
















                        0












                        0








                        0






                        Here's an updated answer, it still doesn't handle hasMany relationships.



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


                        And here's how I use it:



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





                        share|improve this answer














                        Here's an updated answer, it still doesn't handle hasMany relationships.



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


                        And here's how I use it:



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






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Dec 30 '13 at 14:26

























                        answered Feb 16 '13 at 17:44









                        kroofy

                        7961621




                        7961621












                        • I have now an example of adding belongsTo items also: stackoverflow.com/q/20477301/1153884
                          – DelphiLynx
                          Dec 16 '13 at 10:30










                        • Did you figure out how to do hasMany? I ended up doing this which seems to work, but it probably isn't the best way. this.eachRelationship(function(key, relationship){ self._data[key].forEach(function(obj) { newRecord.get(key).addObject(obj); }) });
                          – Cameron Ketcham
                          May 28 '14 at 6:59




















                        • I have now an example of adding belongsTo items also: stackoverflow.com/q/20477301/1153884
                          – DelphiLynx
                          Dec 16 '13 at 10:30










                        • Did you figure out how to do hasMany? I ended up doing this which seems to work, but it probably isn't the best way. this.eachRelationship(function(key, relationship){ self._data[key].forEach(function(obj) { newRecord.get(key).addObject(obj); }) });
                          – Cameron Ketcham
                          May 28 '14 at 6:59


















                        I have now an example of adding belongsTo items also: stackoverflow.com/q/20477301/1153884
                        – DelphiLynx
                        Dec 16 '13 at 10:30




                        I have now an example of adding belongsTo items also: stackoverflow.com/q/20477301/1153884
                        – DelphiLynx
                        Dec 16 '13 at 10:30












                        Did you figure out how to do hasMany? I ended up doing this which seems to work, but it probably isn't the best way. this.eachRelationship(function(key, relationship){ self._data[key].forEach(function(obj) { newRecord.get(key).addObject(obj); }) });
                        – Cameron Ketcham
                        May 28 '14 at 6:59






                        Did you figure out how to do hasMany? I ended up doing this which seems to work, but it probably isn't the best way. this.eachRelationship(function(key, relationship){ self._data[key].forEach(function(obj) { newRecord.get(key).addObject(obj); }) });
                        – Cameron Ketcham
                        May 28 '14 at 6:59













                        0














                        Most simple way I found:



                        function cloneModel(model) {
                        const root = model._internalModel.modelName;
                        const store = model.get('store');
                        let attrs = model.toJSON();

                        attrs.id = `clone-${attrs.id}`;
                        store.pushPayload({
                        [root]: attrs
                        });
                        return store.peekRecord(root, attrs.id);
                        }





                        share|improve this answer


























                          0














                          Most simple way I found:



                          function cloneModel(model) {
                          const root = model._internalModel.modelName;
                          const store = model.get('store');
                          let attrs = model.toJSON();

                          attrs.id = `clone-${attrs.id}`;
                          store.pushPayload({
                          [root]: attrs
                          });
                          return store.peekRecord(root, attrs.id);
                          }





                          share|improve this answer
























                            0












                            0








                            0






                            Most simple way I found:



                            function cloneModel(model) {
                            const root = model._internalModel.modelName;
                            const store = model.get('store');
                            let attrs = model.toJSON();

                            attrs.id = `clone-${attrs.id}`;
                            store.pushPayload({
                            [root]: attrs
                            });
                            return store.peekRecord(root, attrs.id);
                            }





                            share|improve this answer












                            Most simple way I found:



                            function cloneModel(model) {
                            const root = model._internalModel.modelName;
                            const store = model.get('store');
                            let attrs = model.toJSON();

                            attrs.id = `clone-${attrs.id}`;
                            store.pushPayload({
                            [root]: attrs
                            });
                            return store.peekRecord(root, attrs.id);
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 8 '17 at 9:56









                            Jennie Ji

                            629511




                            629511























                                0














                                Here is the simple way to clone your Ember Model with relationships. working fine.



                                Create a Copyable mixin like,



                                import Ember from 'ember';

                                export default Ember.Mixin.create(Ember.Copyable, {

                                copy(deepClone) {
                                var model = this, attrs = model.toJSON(), class_type = model.constructor;
                                var root = Ember.String.decamelize(class_type.toString().split(':')[1]);

                                if(deepClone) {
                                this.eachRelationship(function(key, relationship){
                                if (relationship.kind == 'belongsTo') {
                                attrs[key] = model.get(key).copy(true);
                                } else if(relationship.kind == 'hasMany' && Ember.isArray(attrs[key])) {
                                attrs[key].splice(0);
                                model.get(key).forEach(function(obj) {
                                attrs[key].addObject(obj.copy(true));
                                });
                                }
                                });
                                }
                                return this.store.createRecord(root, attrs);
                                }
                                });


                                Add the mixin in your model,



                                Note: If you want to clone your child model then, you need to include the mixin in child model as well



                                USAGE:




                                1. With relationship : YOURMODEL.copy(true)

                                2. Without relationship : YOURMODEL.copy()






                                share|improve this answer


























                                  0














                                  Here is the simple way to clone your Ember Model with relationships. working fine.



                                  Create a Copyable mixin like,



                                  import Ember from 'ember';

                                  export default Ember.Mixin.create(Ember.Copyable, {

                                  copy(deepClone) {
                                  var model = this, attrs = model.toJSON(), class_type = model.constructor;
                                  var root = Ember.String.decamelize(class_type.toString().split(':')[1]);

                                  if(deepClone) {
                                  this.eachRelationship(function(key, relationship){
                                  if (relationship.kind == 'belongsTo') {
                                  attrs[key] = model.get(key).copy(true);
                                  } else if(relationship.kind == 'hasMany' && Ember.isArray(attrs[key])) {
                                  attrs[key].splice(0);
                                  model.get(key).forEach(function(obj) {
                                  attrs[key].addObject(obj.copy(true));
                                  });
                                  }
                                  });
                                  }
                                  return this.store.createRecord(root, attrs);
                                  }
                                  });


                                  Add the mixin in your model,



                                  Note: If you want to clone your child model then, you need to include the mixin in child model as well



                                  USAGE:




                                  1. With relationship : YOURMODEL.copy(true)

                                  2. Without relationship : YOURMODEL.copy()






                                  share|improve this answer
























                                    0












                                    0








                                    0






                                    Here is the simple way to clone your Ember Model with relationships. working fine.



                                    Create a Copyable mixin like,



                                    import Ember from 'ember';

                                    export default Ember.Mixin.create(Ember.Copyable, {

                                    copy(deepClone) {
                                    var model = this, attrs = model.toJSON(), class_type = model.constructor;
                                    var root = Ember.String.decamelize(class_type.toString().split(':')[1]);

                                    if(deepClone) {
                                    this.eachRelationship(function(key, relationship){
                                    if (relationship.kind == 'belongsTo') {
                                    attrs[key] = model.get(key).copy(true);
                                    } else if(relationship.kind == 'hasMany' && Ember.isArray(attrs[key])) {
                                    attrs[key].splice(0);
                                    model.get(key).forEach(function(obj) {
                                    attrs[key].addObject(obj.copy(true));
                                    });
                                    }
                                    });
                                    }
                                    return this.store.createRecord(root, attrs);
                                    }
                                    });


                                    Add the mixin in your model,



                                    Note: If you want to clone your child model then, you need to include the mixin in child model as well



                                    USAGE:




                                    1. With relationship : YOURMODEL.copy(true)

                                    2. Without relationship : YOURMODEL.copy()






                                    share|improve this answer












                                    Here is the simple way to clone your Ember Model with relationships. working fine.



                                    Create a Copyable mixin like,



                                    import Ember from 'ember';

                                    export default Ember.Mixin.create(Ember.Copyable, {

                                    copy(deepClone) {
                                    var model = this, attrs = model.toJSON(), class_type = model.constructor;
                                    var root = Ember.String.decamelize(class_type.toString().split(':')[1]);

                                    if(deepClone) {
                                    this.eachRelationship(function(key, relationship){
                                    if (relationship.kind == 'belongsTo') {
                                    attrs[key] = model.get(key).copy(true);
                                    } else if(relationship.kind == 'hasMany' && Ember.isArray(attrs[key])) {
                                    attrs[key].splice(0);
                                    model.get(key).forEach(function(obj) {
                                    attrs[key].addObject(obj.copy(true));
                                    });
                                    }
                                    });
                                    }
                                    return this.store.createRecord(root, attrs);
                                    }
                                    });


                                    Add the mixin in your model,



                                    Note: If you want to clone your child model then, you need to include the mixin in child model as well



                                    USAGE:




                                    1. With relationship : YOURMODEL.copy(true)

                                    2. Without relationship : YOURMODEL.copy()







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 29 '17 at 3:31









                                    Akilan M

                                    534




                                    534























                                        0














                                        This will also solve my problem



                                        Account = DS.Model.extend({
                                        name: DS.attr('string'),
                                        playlists: DS.hasMany('playList'),
                                        favoriteSong: DS.belongsTo('song')
                                        });

                                        Duplicate = Ember.Object.extend({});

                                        TemporaryRoute = Ember.Route.extend({
                                        model : function(){
                                        var model = this.store.findAll('account');
                                        var json = model.toJSON();
                                        var duplicateModel = Duplicate.create(json);
                                        this.set('duplicateModel', duplicateModel);
                                        return model;
                                        }
                                        });





                                        share|improve this answer























                                        • findAll returns Promise. so you can't do model.toJSON immediately.
                                          – Ember Freak
                                          Jun 28 '17 at 7:35


















                                        0














                                        This will also solve my problem



                                        Account = DS.Model.extend({
                                        name: DS.attr('string'),
                                        playlists: DS.hasMany('playList'),
                                        favoriteSong: DS.belongsTo('song')
                                        });

                                        Duplicate = Ember.Object.extend({});

                                        TemporaryRoute = Ember.Route.extend({
                                        model : function(){
                                        var model = this.store.findAll('account');
                                        var json = model.toJSON();
                                        var duplicateModel = Duplicate.create(json);
                                        this.set('duplicateModel', duplicateModel);
                                        return model;
                                        }
                                        });





                                        share|improve this answer























                                        • findAll returns Promise. so you can't do model.toJSON immediately.
                                          – Ember Freak
                                          Jun 28 '17 at 7:35
















                                        0












                                        0








                                        0






                                        This will also solve my problem



                                        Account = DS.Model.extend({
                                        name: DS.attr('string'),
                                        playlists: DS.hasMany('playList'),
                                        favoriteSong: DS.belongsTo('song')
                                        });

                                        Duplicate = Ember.Object.extend({});

                                        TemporaryRoute = Ember.Route.extend({
                                        model : function(){
                                        var model = this.store.findAll('account');
                                        var json = model.toJSON();
                                        var duplicateModel = Duplicate.create(json);
                                        this.set('duplicateModel', duplicateModel);
                                        return model;
                                        }
                                        });





                                        share|improve this answer














                                        This will also solve my problem



                                        Account = DS.Model.extend({
                                        name: DS.attr('string'),
                                        playlists: DS.hasMany('playList'),
                                        favoriteSong: DS.belongsTo('song')
                                        });

                                        Duplicate = Ember.Object.extend({});

                                        TemporaryRoute = Ember.Route.extend({
                                        model : function(){
                                        var model = this.store.findAll('account');
                                        var json = model.toJSON();
                                        var duplicateModel = Duplicate.create(json);
                                        this.set('duplicateModel', duplicateModel);
                                        return model;
                                        }
                                        });






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Nov 22 at 11:29









                                        feupeu

                                        409318




                                        409318










                                        answered Jun 28 '17 at 7:33









                                        knu

                                        1




                                        1












                                        • findAll returns Promise. so you can't do model.toJSON immediately.
                                          – Ember Freak
                                          Jun 28 '17 at 7:35




















                                        • findAll returns Promise. so you can't do model.toJSON immediately.
                                          – Ember Freak
                                          Jun 28 '17 at 7:35


















                                        findAll returns Promise. so you can't do model.toJSON immediately.
                                        – Ember Freak
                                        Jun 28 '17 at 7:35






                                        findAll returns Promise. so you can't do model.toJSON immediately.
                                        – Ember Freak
                                        Jun 28 '17 at 7:35




















                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14912425%2fember-clone-model-for-new-record%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Berounka

                                        Sphinx de Gizeh

                                        Different font size/position of beamer's navigation symbols template's content depending on regular/plain...