Skip to content

Commit 4fc401b

Browse files
compwronclaude
andcommitted
fix: Prevent uniqueness validation error when updating case contact types
Fixes Bugsnag error "Validation failed: Case contact has already been taken" (Error URL: https://api.bugsnag.com/projects/5f370b68136a4b0010d15364/events/6924fd6f015b929d46570000) The issue occurred when updating case contacts with contact types. The remove_unwanted_contact_types method used contact_types.clear which marks records for deletion in memory but doesn't immediately execute DELETE statements. When the subsequent update attempted to create new join records, the old records still existed in the database, triggering the uniqueness validation on CaseContactContactType. Changed to use destroy_all which immediately deletes records from the database, ensuring old contact type associations are fully removed before new ones are created. Added regression test to prevent this issue from recurring. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
1 parent df6787f commit 4fc401b

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

app/controllers/case_contacts/form_controller.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ def case_contact_params
165165
# Deletes the current associations (from the join table) only if the submitted form body has the parameters for
166166
# the contact_type ids.
167167
def remove_unwanted_contact_types
168-
@case_contact.contact_types.clear if params.dig(:case_contact, :contact_type_ids)
168+
@case_contact.case_contact_contact_types.destroy_all if params.dig(:case_contact, :contact_type_ids)
169169
end
170170

171171
def remove_nil_draft_ids

spec/requests/case_contacts/form_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,19 @@
234234
case_contact.reload
235235
expect(case_contact.contact_type_ids).to contain_exactly(contact_types.first.id)
236236
end
237+
238+
it "allows re-assigning the same contact type without uniqueness validation error" do
239+
# This test prevents regression of Bugsnag error:
240+
# "Validation failed: Case contact has already been taken"
241+
case_contact.update!(contact_type_ids: [contact_types.first.id])
242+
expect(case_contact.contact_type_ids).to contain_exactly(contact_types.first.id)
243+
244+
# Re-submit form with same contact type (simulates user editing and saving)
245+
request
246+
247+
case_contact.reload
248+
expect(case_contact.contact_type_ids).to contain_exactly(contact_types.first.id)
249+
end
237250
end
238251

239252
context "when contact topic answers in params" do

0 commit comments

Comments
 (0)