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.
This commit is contained in:
Fabien Franzen 2014-10-12 22:00:13 +02:00
parent d69b515c29
commit 58a6c924b3
1 changed files with 16 additions and 5 deletions

View File

@ -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);