Fix DeletedAt marshal and unmarshal, close #3693

This commit is contained in:
Jinzhu 2020-10-30 18:15:07 +08:00
parent 4009ec5816
commit a8141b6cc9
2 changed files with 13 additions and 1 deletions

View File

@ -31,7 +31,7 @@ func (n DeletedAt) MarshalJSON() ([]byte, error) {
func (n *DeletedAt) UnmarshalJSON(b []byte) error { func (n *DeletedAt) UnmarshalJSON(b []byte) error {
err := json.Unmarshal(b, &n.Time) err := json.Unmarshal(b, &n.Time)
if err == nil { if err == nil && !n.Time.IsZero() {
n.Valid = true n.Valid = true
} }
return err return err

View File

@ -1,6 +1,7 @@
package tests_test package tests_test
import ( import (
"encoding/json"
"errors" "errors"
"testing" "testing"
@ -42,3 +43,14 @@ func TestSoftDelete(t *testing.T) {
t.Errorf("Can't find permanently deleted record") t.Errorf("Can't find permanently deleted record")
} }
} }
func TestDeletedAtUnMarshal(t *testing.T) {
expected := &gorm.Model{}
b, _ := json.Marshal(expected)
result := &gorm.Model{}
_ = json.Unmarshal(b, result)
if result.DeletedAt != expected.DeletedAt {
t.Errorf("Failed, result.DeletedAt: %v is not same as expected.DeletedAt: %v", result.DeletedAt, expected.DeletedAt)
}
}