diff --git a/callback_create.go b/callback_create.go index f0709880..a4da39e8 100644 --- a/callback_create.go +++ b/callback_create.go @@ -32,8 +32,18 @@ func beforeCreateCallback(scope *Scope) { func updateTimeStampForCreateCallback(scope *Scope) { if !scope.HasError() { now := NowFunc() - scope.SetColumn("CreatedAt", now) - scope.SetColumn("UpdatedAt", now) + + if createdAtField, ok := scope.FieldByName("CreatedAt"); ok { + if createdAtField.IsBlank { + createdAtField.Set(now) + } + } + + if updatedAtField, ok := scope.FieldByName("UpdatedAt"); ok { + if updatedAtField.IsBlank { + updatedAtField.Set(now) + } + } } } diff --git a/create_test.go b/create_test.go index 7aa181ce..9e17ae94 100644 --- a/create_test.go +++ b/create_test.go @@ -5,6 +5,8 @@ import ( "reflect" "testing" "time" + + "github.com/jinzhu/now" ) func TestCreate(t *testing.T) { @@ -58,6 +60,34 @@ func TestCreate(t *testing.T) { } } +func TestCreateWithExistingTimestamp(t *testing.T) { + user := User{Name: "CreateUserExistingTimestamp"} + + timeA := now.MustParse("2016-01-01") + user.CreatedAt = timeA + user.UpdatedAt = timeA + DB.Save(&user) + + if user.CreatedAt.Format(time.RFC3339) != timeA.Format(time.RFC3339) { + t.Errorf("CreatedAt should not be changed") + } + + if user.UpdatedAt.Format(time.RFC3339) != timeA.Format(time.RFC3339) { + t.Errorf("UpdatedAt should not be changed") + } + + var newUser User + DB.First(&newUser, user.Id) + + if newUser.CreatedAt.Format(time.RFC3339) != timeA.Format(time.RFC3339) { + t.Errorf("CreatedAt should not be changed") + } + + if newUser.UpdatedAt.Format(time.RFC3339) != timeA.Format(time.RFC3339) { + t.Errorf("UpdatedAt should not be changed") + } +} + type AutoIncrementUser struct { User Sequence uint `gorm:"AUTO_INCREMENT"`