diff --git a/lib/relation-definition.js b/lib/relation-definition.js index 1fa299e4..426a043b 100644 --- a/lib/relation-definition.js +++ b/lib/relation-definition.js @@ -257,6 +257,17 @@ Relation.prototype.getCache = function () { return this.modelInstance.__cachedRelations[this.definition.name]; }; +Relation.prototype.callScopeMethod = function(methodName) { + var args = Array.prototype.slice.call(arguments, 1); + var modelInstance = this.modelInstance; + var rel = modelInstance[this.definition.name]; + if (rel && typeof rel[methodName] === 'function') { + return rel[methodName].apply(rel, args); + } else { + throw new Error('Unknown scope method: ' + methodName); + } +} + /** * Fetch the related model(s) - this is a helper method to unify access. * @param (Boolean|Object} condOrRefresh refresh or conditions object @@ -1782,7 +1793,7 @@ EmbedsOne.prototype.create = function (targetModelData, cb) { targetModelData = targetModelData || {}; - var inst = this.build(targetModelData); + var inst = this.callScopeMethod('build', targetModelData); var updateEmbedded = function() { modelInstance.updateAttribute(propertyName, @@ -1854,9 +1865,9 @@ EmbedsOne.prototype.update = function (targetModelData, cb) { }); } } else if (!embeddedInstance && cb) { - this.create(data, db); + this.callScopeMethod('create', data, cb); } else if (!embeddedInstance) { - this.build(data); + this.callScopeMethod('build', data); } }; @@ -2238,7 +2249,7 @@ EmbedsMany.prototype.create = function (targetModelData, cb) { var embeddedList = this.embeddedList(); - var inst = this.build(targetModelData); + var inst = this.callScopeMethod('build', targetModelData); var updateEmbedded = function() { modelInstance.updateAttribute(propertyName, @@ -2619,7 +2630,7 @@ ReferencesMany.prototype.create = function (targetModelData, cb) { var ids = modelInstance[fk] || []; - var inst = this.build(targetModelData); + var inst = this.callScopeMethod('build', targetModelData); inst.save(function(err, inst) { if (err) return cb(err, inst);