From 9297815f997f82af2ab894ce3fd67e5e51382c1f Mon Sep 17 00:00:00 2001 From: Diogo Resende Date: Mon, 4 Mar 2013 20:35:25 +0000 Subject: [PATCH] Fixes hasOne reversed associations not having setAccessor, fixes bug using wrong ID prop instead of the one defined in Model (#55) --- lib/Associations/One.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/lib/Associations/One.js b/lib/Associations/One.js index 48094267..aa6ce1cf 100644 --- a/lib/Associations/One.js +++ b/lib/Associations/One.js @@ -102,23 +102,35 @@ function extendInstance(Model, Instance, Driver, association, opts, cb) { }, enumerable: false }); - if (!association.reversed) { - Object.defineProperty(Instance, association.setAccessor, { - value: function (OtherInstance, cb) { + Object.defineProperty(Instance, association.setAccessor, { + value: function (OtherInstance, cb) { + if (association.reversed) { + Instance.save(function (err) { + if (err) { + return cb(err); + } + + OtherInstance[association.field] = Instance[Model.id]; + + return OtherInstance.save(cb); + }); + } else { OtherInstance.save(function (err) { if (err) { return cb(err); } - Instance[association.field] = OtherInstance.id; + Instance[association.field] = OtherInstance[association.model.id]; return Instance.save(cb); }); + } - return this; - }, - enumerable: false - }); + return this; + }, + enumerable: false + }); + if (association.reversed) { Object.defineProperty(Instance, association.delAccessor, { value: function (cb) { Instance[association.field] = 0;