Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Changeset with partially updated has many association #311

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 7 additions & 3 deletions changeset.go
Expand Up @@ -118,6 +118,7 @@ func (c Changeset) applyAssocMany(field string, mut *Mutation) {
assoc = c.doc.Association(field)
col, _ = assoc.Collection()
muts = make([]Mutation, 0, col.Len())
mutsCount = 0
updatedIDs = make(map[interface{}]struct{})
deletedIDs []interface{}
)
Expand All @@ -130,12 +131,15 @@ func (c Changeset) applyAssocMany(field string, mut *Mutation) {

if ch, ok := chs[pValue]; ok {
updatedIDs[pValue] = struct{}{}
mut := Apply(doc, ch)
muts = append(muts, mut)

if amod := Apply(doc, ch); !amod.IsEmpty() {
muts = append(muts, amod)
if !mut.IsEmpty() {
mutsCount++
}
} else {
muts = append(muts, Apply(doc, newStructset(doc, false)))
mutsCount++
}
}

Expand All @@ -148,7 +152,7 @@ func (c Changeset) applyAssocMany(field string, mut *Mutation) {
}
}

if len(muts) > 0 || len(deletedIDs) > 0 {
if mutsCount > 0 || len(deletedIDs) > 0 {
mut.SetAssoc(field, muts...)
mut.SetDeletedIDs(field, deletedIDs)
}
Expand Down
5 changes: 5 additions & 0 deletions changeset_test.go
Expand Up @@ -503,6 +503,7 @@ func TestChangeset_hasMany(t *testing.T) {
Transactions: []Transaction{
{ID: 11, Item: "Book", Status: "pending"},
{ID: 12, Item: "Eraser", Status: "pending"},
{ID: 13, Item: "Pencil", Status: "pending"},
},
}
snapshots = [][]interface{}{
Expand Down Expand Up @@ -576,6 +577,10 @@ func TestChangeset_hasMany(t *testing.T) {
"address_id": Set("address_id", 0),
},
},
{
Cascade: true,
Mutates: nil, // nil mutates to satisfy repository saveHasMany check
},
},
DeletedIDs: []interface{}{12},
},
Expand Down
8 changes: 5 additions & 3 deletions repository.go
Expand Up @@ -375,7 +375,7 @@ func (r repository) insert(cw contextWrapper, doc *Document, mutation Mutation)
}

// update primary value
if pField != "" {
if pField != "" && !isZero(pValue) {
doc.SetValue(pField, pValue)
}

Expand Down Expand Up @@ -740,8 +740,10 @@ func (r repository) saveHasMany(cw contextWrapper, doc *Document, mutation *Muta
muts[i], muts[updateCount] = muts[updateCount], muts[i]
}

if err := r.update(cw, assocDoc, muts[updateCount], filter); err != nil {
return err
if !muts[updateCount].IsEmpty() {
if err := r.update(cw, assocDoc, muts[updateCount], filter); err != nil {
return err
}
}

updateCount++
Expand Down