From 58a6c924b3a3f3014055f6088a36070bb1ff6533 Mon Sep 17 00:00:00 2001 From: Fabien Franzen Date: Sun, 12 Oct 2014 22:00:13 +0200 Subject: [PATCH] Call relation methods in the right context Before this change, it was impossible to override 'build' and other (custom) relation/scope methods; only the original prototype method was ever called. --- lib/relation-definition.js | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) 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);