Permalink
Browse files

Accept related objects when creating instance #247

  • Loading branch information...
1602 committed Apr 18, 2013
1 parent 8936278 commit 74ef2a63d697e74c629cbb4cd22855311e35de22
Showing with 28 additions and 9 deletions.
  1. +12 −6 lib/model.js
  2. +1 −3 test/hooks.test.js
  3. +15 −0 test/relations.test.js
View
@@ -63,7 +63,14 @@ AbstractClass.prototype._initProperties = function (data, applySetters) {
this.__cachedRelations = data['__cachedRelations'];
}
- for (var i in data) this.__data[i] = this.__dataWas[i] = data[i];
+ for (var i in data) {
+ if (i in properties) {
+ this.__data[i] = this.__dataWas[i] = data[i];
+ } else if (i in ctor.relations) {
+ this.__data[ctor.relations[i].keyFrom] = this.__dataWas[i] = data[i][ctor.relations[i].keyTo];
+ this.__cachedRelations[i] = data[i];
+ }
+ }
if (applySetters === true) {
Object.keys(data).forEach(function (attr) {
@@ -226,8 +233,7 @@ AbstractClass.create = function (data, callback) {
obj.trigger('create', function(createDone) {
obj.trigger('save', function(saveDone) {
- this._adapter().create(modelName, this.constructor._forDB(data), function (err, id, rev) {
- obj._initProperties(data, false);
+ this._adapter().create(modelName, this.constructor._forDB(obj.toObject()), function (err, id, rev) {
if (id) {
obj.__data.id = id;
obj.__dataWas.id = id;
@@ -244,9 +250,9 @@ AbstractClass.create = function (data, callback) {
callback(err, obj);
});
});
- });
- }, data);
- }, data);
+ }, obj);
+ }, obj);
+ }, obj);
}
return obj;
View
@@ -137,7 +137,7 @@ describe('hooks', function() {
User.destroyAll(function() {
User.create({
email: 'james.bond@example.com',
- password: 'secret'
+ password: '53cr3t'
}, function() {
User.findOne({
where: {email: 'james.bond@example.com'}
@@ -306,7 +306,6 @@ describe('hooks', function() {
'afterValidate',
'beforeCreate',
'beforeSave',
- 'afterInitialize',
'afterSave',
'afterCreate'
]);
@@ -323,7 +322,6 @@ describe('hooks', function() {
'afterValidate',
'beforeCreate',
'beforeSave',
- 'afterInitialize',
'afterSave',
'afterCreate'
]);
View
@@ -159,6 +159,21 @@ describe('relations', function() {
});
});
+ it('could accept objects when creating on scope', function(done) {
+ List.create(function(e, list) {
+ should.not.exist(e);
+ should.exist(list);
+ Item.create({list: list}, function(err, item) {
+ should.not.exist(err);
+ should.exist(item);
+ should.exist(item.listId);
+ item.listId.should.equal(list.id);
+ item.__cachedRelations.list.should.equal(list);
+ done();
+ });
+ });
+ });
+
});
describe('hasAndBelongsToMany', function() {

0 comments on commit 74ef2a6

Please sign in to comment.