From 38e7b1a0492dd4282c3cd3b1ddb2b3343661d31f Mon Sep 17 00:00:00 2001 From: Sam Saffron Date: Tue, 18 Aug 2020 10:55:16 +1000 Subject: [PATCH] FIX: when destroying uploads clear card and profile background There is an fk to user_profile that can make destroying uploads fail if they happen to be set as user profile. This ensures we clear this information when destroying uploads. There are more relationships, but this makes some more progress. --- app/models/upload.rb | 5 +++++ spec/models/upload_spec.rb | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/app/models/upload.rb b/app/models/upload.rb index 559ad0cb685..458fb358455 100644 --- a/app/models/upload.rb +++ b/app/models/upload.rb @@ -39,6 +39,11 @@ class Upload < ActiveRecord::Base validates_with UploadValidator + before_destroy do + UserProfile.where(card_background_upload_id: self.id).update_all(card_background_upload_id: nil) + UserProfile.where(profile_background_upload_id: self.id).update_all(profile_background_upload_id: nil) + end + after_destroy do User.where(uploaded_avatar_id: self.id).update_all(uploaded_avatar_id: nil) UserAvatar.where(gravatar_upload_id: self.id).update_all(gravatar_upload_id: nil) diff --git a/spec/models/upload_spec.rb b/spec/models/upload_spec.rb index e95aa43d18e..9049a6d1f1e 100644 --- a/spec/models/upload_spec.rb +++ b/spec/models/upload_spec.rb @@ -413,4 +413,25 @@ describe Upload do "https://#{SiteSetting.s3_upload_bucket}.s3.amazonaws.com/original/1X/#{upload.sha1}.#{upload.extension}?acl" ) end + + context '.destroy' do + + it "can correctly clear information when destroying an upload" do + upload = Fabricate(:upload) + user = Fabricate(:user) + + user.user_profile.update!( + card_background_upload_id: upload.id, + profile_background_upload_id: upload.id + ) + + upload.destroy + + user.user_profile.reload + + expect(user.user_profile.card_background_upload_id).to eq(nil) + expect(user.user_profile.profile_background_upload_id).to eq(nil) + end + + end end