Skip to content

Commit

Permalink
Add Replace support for has many associations
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Dec 25, 2015
1 parent a00fb4d commit 4719ee7
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
3 changes: 2 additions & 1 deletion association.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ func (association *Association) Replace(values ...interface{}) *Association {
if relationship.Kind == "many_to_many" {
association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, query, relationship))
} else if relationship.Kind == "has_one" || relationship.Kind == "has_many" {
query.Update(foreignKeyMap)
fieldValue := reflect.New(association.Field.Field.Type()).Interface()
association.setErr(query.Model(fieldValue).UpdateColumn(foreignKeyMap).Error)
}
return association
}
Expand Down
9 changes: 8 additions & 1 deletion association_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,18 @@ func TestHasMany(t *testing.T) {
var comments3 []Comment
DB.Model(&post).Related(&comments3)
if !compareComments(comments3, []string{"Comment 3"}) {
fmt.Println(comments3)
t.Errorf("Delete an existing resource for has many relations")
}

// Replace
DB.Model(&post).Association("Comments").Replace(&Comment{Content: "Comment 4"}, &Comment{Content: "Comment 5"})

var comments4 []Comment
DB.Model(&post).Related(&comments4)
if !compareComments(comments4, []string{"Comment 4", "Comment 5"}) {
t.Errorf("Replace has many relations")
}

// Clear
}

Expand Down

0 comments on commit 4719ee7

Please sign in to comment.