Ember.js Clone an existing record into the store

Viewed 5572

I am struggling with the concept Ember.js will like. What I want is the following. I have now an existing Ember Data model called Article. Lets say with the id of 1 will be shown on /article/1.

When the user hit the New button they are transitioned to the 'article.new' route. See my routers:

App.Router.map(function () {
   this.resource('article', {path: '/article/:id'});
   this.resource('article.new', {path: "/article/new"});
}

When the user click the Duplicate button when they are at /article/1 the duplicateArticle action gets called. I intuitively do the following in App.ArticleController:

duplicateArticle: function () {
   return this.transitionToRoute('article.new', this.get('model');
}

However that is not going to work. I think because I need an path in my article.new route. However, when a user click on the New button I do not need an ID.

Is there a valid solution to this question?

Edit: My tries so far:

var currentArticle = this.get('model'); 
currentArticle.set('id', null); 
var duplicatedArticle = this.store.createRecord('article', currentArticle); 
duplicatedArticle.save();

and:

var duplicatedArticle = Ember.copy(this.get('model'), true);

and:

 var newArticle = JSON.parse(JSON.stringify(this.get('model')));
 var duplicatedArticle = this.store.createRecord('article', newArticle);
 duplicatedArticle.save();

The last try does work except for belongsTo and hasMany properties.

Is there no Ember way of doing this?

References:

Ember clone model for new record

Is there any way to convert Ember Object into plain javascript object?

Iterating over Ember.js ember-data Record Arrays

How can I clone an Ember Data record, including relationships? (not answered, 75% the same question as me)

.

Update: a simple example with also belongsTo items saved

hasMany does not work. Contribute to this answer if you have a solution!

My final solution without hasMany items is now as follows:

In my actions of my ArticleController:

  duplicateArticle: function () {
        var article = this.get('model').toJSON(),
            self = this;

        // todo implement saving hasMany items

        // set belongsTo items by hand
        article['landcode'] = this.get('landcode');
        article['employee'] = this.get('employee');
        article['cross_selling_article_relation'] = this.get('cross_selling_article_relation');

        var duplicatedArticle = this.store.createRecord('article', article);

        // save and transite to newly created article
        duplicatedArticle.save().then(function (savedArticle) {
            self.transitionToRoute('article', savedArticle.id);
        });
    },
4 Answers
Related