diff --git a/lib/abstract-class.js b/lib/abstract-class.js index 2b9c63df..cb119b68 100644 --- a/lib/abstract-class.js +++ b/lib/abstract-class.js @@ -946,7 +946,7 @@ AbstractClass.belongsTo = function (anotherClass, params) { anotherClass.find(id, function (err,inst) { if (err) return cb(err); if (!inst) return cb(null, null); - if (inst[fk] === this.id) { + if (inst.id === this[fk]) { cb(null, inst); } else { cb(new Error('Permission denied')); @@ -971,12 +971,12 @@ AbstractClass.belongsTo = function (anotherClass, params) { this.__cachedRelations[methodName] = p; } else if (typeof p === 'function') { // acts as async getter if (typeof cachedValue === 'undefined') { - this.__finders__[methodName](this[fk], function(err, inst) { + this.__finders__[methodName].apply(self, [this[fk], function(err, inst) { if (!err) { self.__cachedRelations[methodName] = inst; } p(err, inst); - }); + }]); return this[fk]; } else { p(null, cachedValue); diff --git a/test/common_test.js b/test/common_test.js index e708f8f0..202518fa 100644 --- a/test/common_test.js +++ b/test/common_test.js @@ -532,6 +532,44 @@ function testOrm(schema) { }); }); + it('should navigate variations of belongsTo regardless of column name', function(test){ + + var Dog = schema.define('Dog', { + owner_id : { type: Number, allowNull: true }, + name : { type: String, limit: 64, allowNull: false } + }); + + var Log = schema.define('Log', { + owner_id : { type: Number, allowNull: true }, + name : { type: String, limit: 64, allowNull: false } + }); + + Log.belongsTo(Dog, {as: 'owner', foreignKey: 'owner_id'}); + + Dog.create({name: 'theDog'}, function(err, obj){ + test.ok(obj instanceof Dog); + Log.create({name: 'theLog', owner_id: obj.id}, function(err, obj){ + test.ok(obj instanceof Log); + obj.owner(function(err, obj){ + console.log(err, obj); + test.ok(!err, 'Should not have an error.'); // Before cba174b this would be 'Error: Permission denied' + if(err){ + console.log('Found: ' + err); + } + test.ok(obj, 'Should not find null or undefined.'); // Before cba174b this could be null or undefined. + test.ok(obj instanceof Dog, 'Should find a Dog.'); + if(obj){ // Since test won't stop on fail, have to check before accessing obj.name. + test.ok(obj.name, 'Should have a name.'); + } + if(obj && obj.name){ + test.equal(obj.name, 'theDog', 'The owner of theLog is theDog.'); + } + test.done(); + }); + }); + }); + }); + it('hasMany should support additional conditions', function (test) { User.create(function (e, u) {