From 5b671a84b63b51114df6712353391bba13c8ea3e Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 2 Nov 2013 18:25:01 +0800 Subject: [PATCH] Error message when set primary key --- do.go | 4 +++- gorm_test.go | 12 +++++++----- model.go | 5 ++++- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/do.go b/do.go index a6fe828e..787ce376 100644 --- a/do.go +++ b/do.go @@ -159,7 +159,9 @@ func (s *Do) create() { if !s.hasError() { result := reflect.Indirect(reflect.ValueOf(s.value)) - setFieldValue(result.FieldByName(s.model.primaryKey()), id) + if !setFieldValue(result.FieldByName(s.model.primaryKey()), id) { + fmt.Printf("Can't set primary key for %#v\n", result.Interface()) + } s.saveAfterAssociations() s.err(s.model.callMethod("AfterCreate")) diff --git a/gorm_test.go b/gorm_test.go index 6cacb7de..ece9db44 100644 --- a/gorm_test.go +++ b/gorm_test.go @@ -1002,15 +1002,17 @@ type Category struct { } type Post struct { - Id int64 - Title string - Body string - Comments []Comment - Category Category + Id int64 + CategoryId int64 + Title string + Body string + Comments []Comment + Category Category } type Comment struct { Id int64 + PostId int64 Content string Post Post } diff --git a/model.go b/model.go index 8c742b14..f4b85e19 100644 --- a/model.go +++ b/model.go @@ -309,7 +309,7 @@ func (m *Model) afterAssociations() (fields []Field) { return } -func setFieldValue(field reflect.Value, value interface{}) { +func setFieldValue(field reflect.Value, value interface{}) bool { if field.IsValid() && field.CanAddr() { switch field.Kind() { case reflect.Int, reflect.Int32, reflect.Int64: @@ -320,5 +320,8 @@ func setFieldValue(field reflect.Value, value interface{}) { default: field.Set(reflect.ValueOf(value)) } + return true + } else { + return false } }