Skip to content

Commit

Permalink
fix: correctly set fields holding belongsTo relationships to null whe…
Browse files Browse the repository at this point in the history
…n updated with a null value (#607)
  • Loading branch information
ghusse authored Jan 27, 2021
1 parent 6d0b528 commit 374151f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/services/belongs-to-updater.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,17 @@ class BelongsToUpdater {
const record = await orm.findRecord(this.model, recordId);
const association = Object.values(this.model.associations)
.find((a) => a.associationAccessor === associationName);
const setterName = `set${_.upperFirst(associationName)}`;
const options = { fields: null };

if (association && this.data.data) {
const targetKey = await this._getTargetKey(association);

// NOTICE: Enable model hooks to change fields values during an association update.
const options = { fields: null };
const setterName = `set${_.upperFirst(associationName)}`;
return record[setterName](targetKey, options);
}

return null;
return record[setterName](null, options);
}
}

Expand Down
30 changes: 30 additions & 0 deletions test/databases.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,36 @@ const HasManyDissociator = require('../src/services/has-many-dissociator');
connectionManager.closeConnection();
}
});

it('should update a record when removing a reference to another record', async () => {
expect.assertions(2);
const { models } = initializeSequelize();

try {
const newMember = await new ResourceCreator(models.member, {
id: 421,
name: 'the member',
}).perform();

const newFriend = await new ResourceCreator(models.friend, {
id: 422,
member: newMember,
name: 'my friend',
}).perform();


expect(newFriend.memberId).not.toBeNull();

const result = await new BelongsToUpdater(models.friend, null, null, {
recordId: newFriend.id,
associationName: 'member',
}, { data: null }).perform();

expect(result.memberId).toBeNull();
} finally {
connectionManager.closeConnection();
}
});
});
describe('update a record on a collection with a foreign key non pointing to a primary key', () => {
it('should update a record', async () => {
Expand Down

0 comments on commit 374151f

Please sign in to comment.