FIX: Ensure uploads are linked to post when revising a post

FIX: Ensure uploads are linked to post when revising a post

Editing a post didn’t update the post_uploads right away. Instead it relied on the CookedPostProcessor. This can lead to an inconsistent state if uploads are added or removed during an edit and, for some reason, the ProcessPost job doesn’t run (successfully). This inconsistency leads to missing uploads, because the newly added uploads appear to be unused and will be deleted by the CleanUpUploads job. In addition to that, uploads, which got removed during the edit, appear to be still in use and won’t be deleted by the background job.

This commit ensures that the post_uploads are updated during the edit without relying on a background job.

diff --git a/lib/post_revisor.rb b/lib/post_revisor.rb
index 0b7a650..a9912d6 100644
--- a/lib/post_revisor.rb
+++ b/lib/post_revisor.rb
@@ -386,6 +386,7 @@ class PostRevisor
     @post.extract_quoted_post_numbers
 
     @post_successfully_saved = @post.save(validate: @validate_post)
+    @post.link_post_uploads
     @post.save_reply_relationships
 
     # post owner changed
diff --git a/spec/components/post_revisor_spec.rb b/spec/components/post_revisor_spec.rb
index 78ee3c2..a6a2cb4 100644
--- a/spec/components/post_revisor_spec.rb
+++ b/spec/components/post_revisor_spec.rb
@@ -951,5 +951,37 @@ describe PostRevisor do
         end
       end
     end
+
+    context "uploads" do
+      let(:image1) { Fabricate(:upload) }
+      let(:image2) { Fabricate(:upload) }
+      let(:image3) { Fabricate(:upload) }
+      let(:image4) { Fabricate(:upload) }
+      let(:post_args) do
+        {
+          user: user,
+          topic: topic,
+          raw: <<~RAW
+            This is a post with multiple uploads
+            ![image1](#{image1.short_url})
+            ![image2](#{image2.short_url})
+          RAW
+        }
+      end
+
+      it "updates linked post uploads" do
+        post.link_post_uploads
+        expect(post.post_uploads.pluck(:upload_id)).to contain_exactly(image1.id, image2.id)
+
+        subject.revise!(user, raw: <<~RAW)
+            This is a post with multiple uploads
+            ![image2](#{image2.short_url})
+            ![image3](#{image3.short_url})
+            ![image4](#{image4.short_url})
+        RAW
+
+        expect(post.reload.post_uploads.pluck(:upload_id)).to contain_exactly(image2.id, image3.id, image4.id)
+      end
+    end
   end
 end

GitHub sha: 81395be4

2 Likes