From ee05ebcca6eb389ed957e68bba55afee707e0de6 Mon Sep 17 00:00:00 2001 From: Anatoliy Chakkaev Date: Thu, 18 Apr 2013 23:00:15 +0400 Subject: [PATCH] Relations passed to belongsTo.add --- lib/relations.js | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/lib/relations.js b/lib/relations.js index e1e76076..0eddb057 100644 --- a/lib/relations.js +++ b/lib/relations.js @@ -9,6 +9,14 @@ var defineScope = require('./scope.js').defineScope; */ var Model = require('./model.js'); +Model.relationNameFor = function relationNameFor(foreignKey) { + for (var rel in this.relations) { + if (this.relations[rel].type === 'belongsTo' && this.relations[rel].keyFrom === foreignKey) { + return rel; + } + } +}; + /** * Declare hasMany relation * @@ -36,7 +44,7 @@ Model.hasMany = function hasMany(anotherClass, params) { i8n.camelize(i8n.pluralize(anotherClass.modelName), true); var fk = params.foreignKey || i8n.camelize(thisClassName + '_id', true); - this.relations[params['as']] = { + this.relations[methodName] = { type: 'hasMany', keyFrom: 'id', keyTo: fk, @@ -57,12 +65,16 @@ Model.hasMany = function hasMany(anotherClass, params) { done = data; data = {}; } + if ('function' !== typeof done) { + done = function() {}; + } + var self = this; var id = this.id; anotherClass.create(data, function(err, ac) { if (err) return done(err, ac); var d = {}; - d[fk] = id; - d[fk2] = ac.id; + d[params.through.relationNameFor(fk)] = self; + d[params.through.relationNameFor(fk2)] = ac; params.through.create(d, function(e) { if (e) { ac.destroy(function() { @@ -76,9 +88,12 @@ Model.hasMany = function hasMany(anotherClass, params) { }; scopeMethods.add = function(acInst, done) { var data = {}; - data[fk] = this.id; - data[fk2] = acInst.id || acInst; - params.through.findOrCreate({where: data}, done); + var query = {}; + query[fk] = this.id; + data[params.through.relationNameFor(fk)] = this; + query[fk2] = acInst.id || acInst; + data[params.through.relationNameFor(fk2)] = acInst; + params.through.findOrCreate({where: query}, data, done); }; scopeMethods.remove = function(acInst, done) { var self = this;