Merge branch 'BuddyHOPP-fix/350-create-batch-hasmany-relation'

This commit is contained in:
Raymond Feng 2014-11-13 12:56:38 -08:00
commit 9c575a3902
2 changed files with 199 additions and 160 deletions

View File

@ -1570,14 +1570,26 @@ HasMany.prototype.create = function (targetModelData, cb) {
targetModelData = {}; targetModelData = {};
} }
targetModelData = targetModelData || {}; targetModelData = targetModelData || {};
targetModelData[fk] = modelInstance[pk];
this.definition.applyProperties(modelInstance, targetModelData); var fkAndProps = function(item) {
item[fk] = modelInstance[pk];
self.definition.applyProperties(modelInstance, item);
};
var apply = function(data, fn) {
if (Array.isArray(data)) {
data.forEach(fn);
} else {
fn(data);
}
};
apply(targetModelData, fkAndProps);
modelTo.create(targetModelData, function(err, targetModel) { modelTo.create(targetModelData, function(err, targetModel) {
if(!err) { if(!err) {
// Refresh the cache //Refresh the cache
self.addToCache(targetModel); apply(targetModel, self.addToCache.bind(self));
cb && cb(err, targetModel); cb && cb(err, targetModel);
} else { } else {
cb && cb(err); cb && cb(err);

View File

@ -61,6 +61,13 @@ describe('relations', function () {
db.autoupdate(done); db.autoupdate(done);
}); });
describe('with scope', function() {
before(function (done) {
Book.hasMany(Chapter);
done();
});
it('should build record on scope', function (done) { it('should build record on scope', function (done) {
Book.create(function (err, book) { Book.create(function (err, book) {
var c = book.chapters.build(); var c = book.chapters.build();
@ -80,6 +87,25 @@ describe('relations', function () {
}); });
}); });
it('should create a batch of records on scope', function (done) {
var chapters = [
{name: 'a'},
{name: 'z'},
{name: 'c'}
];
Book.create(function (err, book) {
book.chapters.create(chapters, function (err, chs) {
should.not.exist(err);
should.exist(chs);
chs.should.have.lengthOf(chapters.length);
chs.forEach(function(c) {
c.bookId.should.equal(book.id);
});
done();
});
});
});
it('should fetch all scoped instances', function (done) { it('should fetch all scoped instances', function (done) {
Book.create(function (err, book) { Book.create(function (err, book) {
book.chapters.create({name: 'a'}, function () { book.chapters.create({name: 'a'}, function () {
@ -244,6 +270,7 @@ describe('relations', function () {
done(); done();
}); });
}); });
});
}); });