不要怂,就是干,撸起袖子干!

Commit 3e048c74 by sdepold

merge: added selective save

2 parents b928d775 3c4cbad3
......@@ -44,7 +44,9 @@ module.exports = (function() {
obj[accessor] = function(associatedObject) {
obj[self.identifier] = associatedObject ? associatedObject.id : null
return obj.save()
// passes the changed field to save, so only that field get updated.
return obj.save([self.identifier])
}
return this
......
......@@ -81,7 +81,20 @@ module.exports = (function() {
}
})
DAO.prototype.save = function() {
// if an array with field names is passed to save()
// only those fields will be updated
DAO.prototype.save = function(fields) {
var self = this
, values = fields ? {} : this.values;
if(fields) {
fields.forEach(function(field) {
if(self.values[field]) {
values[field] = self.values[field]
}
});
}
var updatedAtAttr = this.__options.underscored ? 'updated_at' : 'updatedAt'
if(this.__options.timestamps && this.hasOwnProperty(updatedAtAttr))
......@@ -92,7 +105,7 @@ module.exports = (function() {
} else {
var identifier = this.__options.hasPrimaryKeys ? this.primaryKeyValues : this.id
, tableName = this.__factory.tableName
, query = this.QueryInterface.update(this, tableName, this.values, identifier)
, query = this.QueryInterface.update(this, tableName, values, identifier)
return query
}
......
......@@ -333,6 +333,51 @@ describe('DAO', function() {
})
describe('save', function() {
it('only updates fields in passed array', function() {
var user = null
, user2 = null
, userId = null
, date = new Date(1990, 01, 01)
Helpers.async(function(done) {
User.create({
username: 'foo',
birthDate: new Date()
}).success(function(_user) {
user = _user
done()
}).error(function(err) {
console.log(err)
})
})
Helpers.async(function(done) {
user.username = 'fizz'
user.birthDate = date
done()
})
Helpers.async(function(done) {
user.save(['username']).success(function(){
// re-select user
User.find(user.id).success(function(_user2) {
user2 = _user2
done()
})
})
})
Helpers.async(function(done) {
// name should have changed
expect(user2.username).toEqual('fizz')
// bio should be unchanged
expect(user2.birthDate).toNotEqual(date)
done()
})
})
it("stores an entry in the database", function() {
var username = 'user'
, user = User.build({
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!