From bcb057c27504bff49de34f894709df3582706500 Mon Sep 17 00:00:00 2001 From: Campbell Allen Date: Fri, 20 May 2022 11:22:34 +0100 Subject: [PATCH] avoid unique validation errors switch to upserting subjects --- app/services/import/subject.rb | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/app/services/import/subject.rb b/app/services/import/subject.rb index 5e30f5b..c3cd8b8 100644 --- a/app/services/import/subject.rb +++ b/app/services/import/subject.rb @@ -10,9 +10,25 @@ def initialize(zooniverse_subject_id, context) end def run - subject = ::Subject.find_or_create_by!(context_id: context.id, zooniverse_subject_id: zooniverse_subject_id) + subject = upsert_subject SubjectBackfillerJob.perform_async(subject.id) subject end + + private + + def upsert_subject + # use upsert to avoid collisions for inserting rows + upsert_results = ::Subject.upsert_all( + [{ + context_id: context.id, + zooniverse_subject_id: zooniverse_subject_id + }], + unique_by: %i[zooniverse_subject_id context_id], + update_only: [:context_id] # must have an update clause to get a result set + ) + upserted_subject_id = upsert_results.to_a.first['id'] + ::Subject.find(upserted_subject_id) + end end end