From a8141b6cc92b15d7d6f7936942749a5e044f9c9a Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 30 Oct 2020 18:15:07 +0800 Subject: [PATCH] Fix DeletedAt marshal and unmarshal, close #3693 --- soft_delete.go | 2 +- tests/soft_delete_test.go | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/soft_delete.go b/soft_delete.go index b3280ff7..f3272246 100644 --- a/soft_delete.go +++ b/soft_delete.go @@ -31,7 +31,7 @@ func (n DeletedAt) MarshalJSON() ([]byte, error) { func (n *DeletedAt) UnmarshalJSON(b []byte) error { err := json.Unmarshal(b, &n.Time) - if err == nil { + if err == nil && !n.Time.IsZero() { n.Valid = true } return err diff --git a/tests/soft_delete_test.go b/tests/soft_delete_test.go index 40d46fd8..c77675f7 100644 --- a/tests/soft_delete_test.go +++ b/tests/soft_delete_test.go @@ -1,6 +1,7 @@ package tests_test import ( + "encoding/json" "errors" "testing" @@ -42,3 +43,14 @@ func TestSoftDelete(t *testing.T) { 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) + } +}