From e94787724bab9d5154fdc0dcd8a0c190851d618d Mon Sep 17 00:00:00 2001 From: Rick O'Toole Date: Tue, 7 Feb 2012 19:55:49 -1000 Subject: [PATCH] changed belongsTo so grabs the belongs to relationship properly --- lib/abstract-class.js | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/lib/abstract-class.js b/lib/abstract-class.js index d5bc85c4..4521dc52 100644 --- a/lib/abstract-class.js +++ b/lib/abstract-class.js @@ -489,20 +489,31 @@ AbstractClass.hasMany = function (anotherClass, params) { AbstractClass.belongsTo = function (anotherClass, params) { var methodName = params.as; var fk = params.foreignKey; - this.schema.defineForeignKey(anotherClass.modelName, fk); - this.prototype[methodName] = function (p, cb) { + this.prototype['__finders__'] = this.prototype['__finders__'] || {} + + this.prototype['__finders__'][methodName] = function (id, cb) { + anotherClass.find(id, function (err,inst) { + if (err) return cb(err); + if (inst[fk] === this.id) { + cb(null, inst); + } else { + cb(new Error('Permission denied')); + } + }.bind(this)); + } + + this.prototype[methodName] = function (p) { if (p instanceof AbstractClass) { // acts as setter this[fk] = p.id; this.cachedRelations[methodName] = p; } else if (typeof p === 'function') { // acts as async getter - this.find(this[fk], function (err, obj) { - if (err) return p(err); - this.cachedRelations[methodName] = obj; - }.bind(this)); + this.__finders__[methodName](this[fk],p); } else if (!p) { // acts as sync getter - return this.cachedRelations[methodName] || this[fk]; + return this[fk]; } }; + console.log(this.prototype); + }; AbstractClass.scope = function (name, params) {