Skip to content

Commit

Permalink
Fixes cache for hasOne associations (#339)
Browse files Browse the repository at this point in the history
  • Loading branch information
dresende committed Sep 18, 2013
1 parent d4eb2d0 commit 3303e8b
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions lib/Associations/One.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,17 @@ function extendInstance(Model, Instance, Driver, association, opts) {
opts = {};
}

var saveAndReturn = function (err, Assoc) {
if (!err) {
Instance[association.name] = Assoc;
}

return cb(err, Assoc);
};

if (association.reversed) {
if (util.hasValues(Instance, Model.id)) {
association.model.find(util.getConditions(Model, Object.keys(association.field), Instance), opts, cb);
association.model.find(util.getConditions(Model, Object.keys(association.field), Instance), opts, saveAndReturn);
} else {
cb(null);
}
Expand All @@ -172,10 +180,10 @@ function extendInstance(Model, Instance, Driver, association, opts) {
if (err || !util.hasValues(instance, Object.keys(association.field))) {
return cb(null);
}
association.model.get(util.values(instance, Object.keys(association.field)), opts, cb);
association.model.get(util.values(instance, Object.keys(association.field)), opts, saveAndReturn);
});
} else if (util.hasValues(Instance, Object.keys(association.field))) {
association.model.get(util.values(Instance, Object.keys(association.field)), opts, cb);
association.model.get(util.values(Instance, Object.keys(association.field)), opts, saveAndReturn);
} else {
cb(null);
}
Expand Down Expand Up @@ -227,6 +235,8 @@ function extendInstance(Model, Instance, Driver, association, opts) {
return cb(err);
}

Instance[association.name] = OtherInstance;

util.populateConditions(association.model, Object.keys(association.field), OtherInstance, Instance);

return Instance.save({}, { saveAssociations: false }, cb);
Expand All @@ -243,7 +253,13 @@ function extendInstance(Model, Instance, Driver, association, opts) {
for (var k in association.field) {
Instance[k] = null;
}
Instance.save({}, { saveAssociations: false }, cb);
Instance.save({}, { saveAssociations: false }, function (err) {
if (!err) {
delete Instance[association.name];
}

return cb();
});

return this;
},
Expand All @@ -270,13 +286,7 @@ function autoFetchInstance(Instance, association, opts, cb) {
// callback, and hence this lookup would complete at an arbitrary point in the future.
// The associated entity should probably be fetched when the instance is persisted.
if (Instance.isPersisted()) {
Instance[association.getAccessor]({ autoFetchLimit: opts.autoFetchLimit - 1 }, function (err, Assoc) {
if (!err) {
Instance[association.name] = Assoc;
}

return cb();
});
Instance[association.getAccessor]({ autoFetchLimit: opts.autoFetchLimit - 1 }, cb);
} else {
return cb();
}
Expand Down

0 comments on commit 3303e8b

Please sign in to comment.