Accept related objects when creating instance #247
This commit is contained in:
parent
eecbd32d07
commit
83027f9ead
18
lib/model.js
18
lib/model.js
|
@ -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;
|
||||
|
|
|
@ -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'
|
||||
]);
|
||||
|
|
|
@ -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() {
|
||||
|
|
Loading…
Reference in New Issue