Skip to content

Commit

Permalink
Relations passed to belongsTo.add
Browse files Browse the repository at this point in the history
  • Loading branch information
1602 committed Apr 18, 2013
1 parent 1bf0cd4 commit 98b22bc
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions lib/relations.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down Expand Up @@ -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,
Expand All @@ -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() {
Expand All @@ -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;
Expand Down

0 comments on commit 98b22bc

Please sign in to comment.