Merge pull request #358 from clarkorz/fix/beforeCreate-belongsTo

fix recursive calls if create belongsTo model in beforeCreate hook
This commit is contained in:
Raymond Feng 2015-01-14 14:42:29 -08:00
commit 4aeb831bd5
2 changed files with 29 additions and 4 deletions

View File

@ -1193,11 +1193,16 @@ BelongsTo.prototype.create = function(targetModelData, cb) {
modelTo.create(targetModelData, function(err, targetModel) { modelTo.create(targetModelData, function(err, targetModel) {
if(!err) { if(!err) {
modelInstance[fk] = targetModel[pk]; modelInstance[fk] = targetModel[pk];
modelInstance.save(function(err, inst) { if (modelInstance.isNewRecord()) {
if (cb && err) return cb && cb(err);
self.resetCache(targetModel); self.resetCache(targetModel);
cb && cb(err, 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 { } else {
cb && cb(err); cb && cb(err);
} }

View File

@ -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 () { describe('belongsTo with scope', function () {
@ -1680,7 +1697,10 @@ describe('relations', function () {
p.personId.should.equal(person.id); p.personId.should.equal(person.id);
person.name.should.equal('Fred'); person.name.should.equal('Fred');
person.passportNotes.should.equal('Some notes...'); person.passportNotes.should.equal('Some notes...');
done(); p.save(function (err, passport) {
should.not.exists(err);
done();
});
}); });
}); });