From d7d9e24e1ef251b76ec847f9c7153489f6e4d1a9 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 26 Mar 2014 08:26:45 +0800 Subject: [PATCH] Add test for anonymous field --- main_test.go | 30 +++++++++++++++++++++++++++--- scope.go | 2 +- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/main_test.go b/main_test.go index 32d9ac62..540c1e13 100644 --- a/main_test.go +++ b/main_test.go @@ -35,6 +35,11 @@ func (i *Num) Scan(src interface{}) error { return nil } +type Role struct { + Id int64 + Name string +} + type User struct { Id int64 // Id: Primary key Age int64 @@ -53,9 +58,11 @@ type User struct { When time.Time CreditCard CreditCard Latitude float64 - PasswordHash []byte - IgnoreMe int64 `sql:"-"` - IgnoreStringSlice []string `sql:"-"` + Role + RoleId int64 + PasswordHash []byte + IgnoreMe int64 `sql:"-"` + IgnoreStringSlice []string `sql:"-"` } type CreditCard struct { @@ -143,6 +150,7 @@ func init() { db.Exec("drop table emails;") db.Exec("drop table addresses") db.Exec("drop table credit_cards") + db.Exec("drop table roles") if err = db.CreateTable(&User{}).Error; err != nil { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) @@ -164,6 +172,10 @@ func init() { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } + if err = db.AutoMigrate(Role{}).Error; err != nil { + panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) + } + var shortForm = "2006-01-02 15:04:05" t1, _ = time.Parse(shortForm, "2000-10-27 12:02:40") t2, _ = time.Parse(shortForm, "2002-01-01 00:00:00") @@ -1729,6 +1741,18 @@ func TestHaving(t *testing.T) { } } +func TestAnonymousField(t *testing.T) { + user := User{Name: "anonymous_field", Role: Role{Name: "admin"}} + db.Save(&user) + + var user2 User + db.First(&user2, "name = ?", "anonymous_field") + db.Model(&user2).Related(&user2.Role) + if user2.Role.Name != "admin" { + t.Errorf("Should be able to get anonymous field") + } +} + func TestExecRawSql(t *testing.T) { db.Exec("update users set name=? where name in (?)", "jinzhu", []string{"1", "2", "3"}) if db.Where("name in (?)", []string{"1", "2", "3"}).First(&User{}).Error != gorm.RecordNotFound { diff --git a/scope.go b/scope.go index 78742d89..40697f9a 100644 --- a/scope.go +++ b/scope.go @@ -227,7 +227,7 @@ func (scope *Scope) Fields() []*Field { scopeTyp := indirectValue.Type() for i := 0; i < scopeTyp.NumField(); i++ { fieldStruct := scopeTyp.Field(i) - if fieldStruct.Anonymous || !ast.IsExported(fieldStruct.Name) { + if !ast.IsExported(fieldStruct.Name) { continue }