From edc1f785302dc893242ce864cc64020cddd2cdb7 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 11 Sep 2015 07:35:57 +0800 Subject: [PATCH] Fix calculate fields for the first time --- field_test.go | 34 ++++++++++++++++++++++++++++++++++ model_struct.go | 8 ++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 field_test.go diff --git a/field_test.go b/field_test.go new file mode 100644 index 00000000..d19b3b1b --- /dev/null +++ b/field_test.go @@ -0,0 +1,34 @@ +package gorm_test + +import ( + "testing" + + "github.com/jinzhu/gorm" +) + +type CalculateField struct { + gorm.Model + Name string + Children []CalculateFieldChild + Category CalculateFieldCategory +} + +type CalculateFieldChild struct { + gorm.Model + CalculateFieldID uint + Name string +} + +type CalculateFieldCategory struct { + gorm.Model + CalculateFieldID uint + Name string +} + +func TestCalculateField(t *testing.T) { + var field CalculateField + fields := DB.NewScope(&field).Fields() + if fields["children"].Relationship == nil || fields["category"].Relationship == nil { + t.Errorf("Should calculate fields correctly for the first time") + } +} diff --git a/model_struct.go b/model_struct.go index f6e035f8..608c70d4 100644 --- a/model_struct.go +++ b/model_struct.go @@ -153,7 +153,8 @@ func (scope *Scope) GetModelStruct() *ModelStruct { } } - defer func() { + var finished = make(chan bool) + go func(finished chan bool) { for _, field := range fields { if !field.IsIgnored { fieldStruct := field.Struct @@ -365,10 +366,13 @@ func (scope *Scope) GetModelStruct() *ModelStruct { } modelStruct.StructFields = append(modelStruct.StructFields, field) } - }() + finished <- true + }(finished) modelStructs[scopeType] = &modelStruct + <-finished + return &modelStruct }