diff --git a/embedded_struct_test.go b/embedded_struct_test.go index 91dd0563..5f8ece57 100644 --- a/embedded_struct_test.go +++ b/embedded_struct_test.go @@ -71,3 +71,21 @@ func TestSaveAndQueryEmbeddedStruct(t *testing.T) { } } } + +func TestEmbeddedPointerTypeStruct(t *testing.T) { + type HNPost struct { + *BasePost + Upvotes int32 + } + + DB.Create(&HNPost{BasePost: &BasePost{Title: "embedded_pointer_type"}}) + + var hnPost HNPost + if err := DB.First(&hnPost, "title = ?", "embedded_pointer_type").Error; err != nil { + t.Errorf("No error should happen when find embedded pointer type, but got %v", err) + } + + if hnPost.Title != "embedded_pointer_type" { + t.Errorf("Should find correct value for embedded pointer type") + } +} diff --git a/scope.go b/scope.go index cdb772ca..14baf631 100644 --- a/scope.go +++ b/scope.go @@ -115,6 +115,9 @@ func (scope *Scope) Fields() []*Field { if isStruct { fieldValue := indirectScopeValue for _, name := range structField.Names { + if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() { + fieldValue.Set(reflect.New(fieldValue.Type().Elem())) + } fieldValue = reflect.Indirect(fieldValue).FieldByName(name) } fields = append(fields, &Field{StructField: structField, Field: fieldValue, IsBlank: isBlank(fieldValue)})