From fb09befb9b0489da50eeb3580a80cae2c3091eb1 Mon Sep 17 00:00:00 2001 From: elgris Date: Tue, 12 Jul 2016 10:10:18 +0300 Subject: [PATCH] Adds processing of ignored fields on Update --- migration_test.go | 2 +- scope.go | 2 +- update_test.go | 31 +++++++++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/migration_test.go b/migration_test.go index ec33efc1..7fdf7bf8 100644 --- a/migration_test.go +++ b/migration_test.go @@ -252,7 +252,7 @@ func runMigration() { DB.Exec(fmt.Sprintf("drop table %v;", table)) } - values := []interface{}{&Short{}, &ReallyLongThingThatReferencesShort{}, &ReallyLongTableNameToTestMySQLNameLengthLimit{}, &NotSoLongTableName{}, &Product{}, &Email{}, &Address{}, &CreditCard{}, &Company{}, &Role{}, &Language{}, &HNPost{}, &EngadgetPost{}, &Animal{}, &User{}, &JoinTable{}, &Post{}, &Category{}, &Comment{}, &Cat{}, &Dog{}, &Toy{}} + values := []interface{}{&Short{}, &ReallyLongThingThatReferencesShort{}, &ReallyLongTableNameToTestMySQLNameLengthLimit{}, &NotSoLongTableName{}, &Product{}, &Email{}, &Address{}, &CreditCard{}, &Company{}, &Role{}, &Language{}, &HNPost{}, &EngadgetPost{}, &Animal{}, &User{}, &JoinTable{}, &Post{}, &Category{}, &Comment{}, &Cat{}, &Dog{}, &Toy{}, &ElementWithIgnoredField{}} for _, value := range values { DB.DropTable(value) } diff --git a/scope.go b/scope.go index 48a87f58..c37fc078 100644 --- a/scope.go +++ b/scope.go @@ -835,7 +835,7 @@ func convertInterfaceToMap(values interface{}) map[string]interface{} { } default: for _, field := range (&Scope{Value: values}).Fields() { - if !field.IsBlank { + if !field.IsBlank && !field.IsIgnored { attrs[field.DBName] = field.Field.Interface() } } diff --git a/update_test.go b/update_test.go index bdf01091..82dd6e64 100644 --- a/update_test.go +++ b/update_test.go @@ -419,6 +419,37 @@ func TestUpdatesWithBlankValues(t *testing.T) { } } +type ElementWithIgnoredField struct { + Id int64 + Value string + IgnoredField int64 `sql:"-"` +} + +func (e ElementWithIgnoredField) TableName() string { + return "element_with_ignored_field" +} + +func TestUpdatesTableWithIgnoredValues(t *testing.T) { + elem := ElementWithIgnoredField{Value: "foo", IgnoredField: 10} + DB.LogMode(true) + DB.Save(&elem) + + DB.Table(elem.TableName()). + Where("id = ?", elem.Id). + // DB.Model(&ElementWithIgnoredField{Id: elem.Id}). + Updates(&ElementWithIgnoredField{Value: "bar", IgnoredField: 100}) + + var elem1 ElementWithIgnoredField + err := DB.First(&elem1, elem.Id).Error + if err != nil { + t.Errorf("error getting an element from database: %s", err.Error()) + } + + if elem1.IgnoredField != 0 { + t.Errorf("element's ignored field should not be updated") + } +} + func TestUpdateDecodeVirtualAttributes(t *testing.T) { var user = User{ Name: "jinzhu",