From 17c8576097cadff259c32e58b43a58c4cbbb269e Mon Sep 17 00:00:00 2001 From: Fabien Franzen Date: Wed, 1 Apr 2015 16:59:21 +0200 Subject: [PATCH] Save parent model of embedded relations --- lib/relation-definition.js | 30 ++++++++++++++++++++++-------- test/relations.test.js | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/lib/relation-definition.js b/lib/relation-definition.js index d374882a..aba111cd 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -1900,10 +1900,17 @@ EmbedsOne.prototype.create = function (targetModelData, cb) { var inst = this.callScopeMethod('build', targetModelData); var updateEmbedded = function() { - modelInstance.updateAttribute(propertyName, - inst, function(err) { - cb(err, err ? null : inst); - }); + if (modelInstance.isNewRecord()) { + modelInstance.setAttribute(propertyName, inst); + modelInstance.save(function(err) { + cb(err, err ? null : inst); + }); + } else { + modelInstance.updateAttribute(propertyName, + inst, function(err) { + cb(err, err ? null : inst); + }); + } }; if (this.definition.options.persistent) { @@ -2385,10 +2392,17 @@ EmbedsMany.prototype.create = function (targetModelData, cb) { var inst = this.callScopeMethod('build', targetModelData); var updateEmbedded = function() { - modelInstance.updateAttribute(propertyName, - embeddedList, function(err, modelInst) { - cb(err, err ? null : inst); - }); + if (modelInstance.isNewRecord()) { + modelInstance.setAttribute(propertyName, embeddedList); + modelInstance.save(function(err) { + cb(err, err ? null : inst); + }); + } else { + modelInstance.updateAttribute(propertyName, + embeddedList, function(err) { + cb(err, err ? null : inst); + }); + } }; if (this.definition.options.persistent) { diff --git a/test/relations.test.js b/test/relations.test.js index 9cebef96..3dd7acc4 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -2407,6 +2407,17 @@ describe('relations', function () { }); }); + it('should save an unsaved model', function(done) { + var p = new Person({name: 'Fred'}); + p.isNewRecord().should.be.true; + p.passportItem.create({name: 'Fredric'}, function(err, passport) { + should.not.exist(err); + p.passport.should.equal(passport); + p.isNewRecord().should.be.false; + done(); + }); + }); + }); describe('embedsOne - persisted model', function () { @@ -2710,6 +2721,17 @@ describe('relations', function () { done(); }); }); + + it('should save an unsaved model', function(done) { + var p = new Person({name: 'Fred'}); + p.isNewRecord().should.be.true; + p.addressList.create({ street: 'Street 4' }, function(err, address) { + should.not.exist(err); + address.street.should.equal('Street 4'); + p.isNewRecord().should.be.false; + done(); + }); + }); });