diff --git a/lib/relation-definition.js b/lib/relation-definition.js index 80b9dca0..504eb939 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -1193,11 +1193,16 @@ BelongsTo.prototype.create = function(targetModelData, cb) { modelTo.create(targetModelData, function(err, targetModel) { if(!err) { modelInstance[fk] = targetModel[pk]; - modelInstance.save(function(err, inst) { - if (cb && err) return cb && cb(err); + if (modelInstance.isNewRecord()) { self.resetCache(targetModel); cb && cb(err, targetModel); - }); + } else { + modelInstance.save(function(err, inst) { + if (cb && err) return cb && cb(err); + self.resetCache(targetModel); + cb && cb(err, targetModel); + }); + } } else { cb && cb(err); } diff --git a/test/relations.test.js b/test/relations.test.js index f6cd3680..7d8bed84 100644 --- a/test/relations.test.js +++ b/test/relations.test.js @@ -1657,6 +1657,23 @@ describe('relations', function () { }); }); + it('should allow to create belongsTo model in beforeCreate hook', function (done) { + var mind; + Fear.beforeCreate = function (next) { + this.mind.create(function (err, m) { + mind = m; + if (err) next(err); else next(); + }); + }; + Fear.create(function (err, fear) { + should.not.exists(err); + should.exists(fear); + fear.mindId.should.be.equal(mind.id); + should.exists(fear.mind()); + done(); + }); + }); + }); describe('belongsTo with scope', function () { @@ -1680,7 +1697,10 @@ describe('relations', function () { p.personId.should.equal(person.id); person.name.should.equal('Fred'); person.passportNotes.should.equal('Some notes...'); - done(); + p.save(function (err, passport) { + should.not.exists(err); + done(); + }); }); });