Fix #4913: Invalid replacements created if an error is raised during replacement

Perform the replacement in a before_create callback so that it runs in a
transaction and if it fails, the transaction will rollback and the
replacement record won't be created.

Doing the replacement in a transaction isn't great because, for one
thing, it could hold the transaction open a long time, which isn't good
for the database. And two, if the transaction rolls back, the database
changes will be undone, but if the replacement file has already been saved
to disk, then it won't be undone, which could result in a dangling file.
This commit is contained in:
evazion
2022-02-01 00:25:31 -06:00
parent 770a6c339a
commit 60a13fd2d5
7 changed files with 37 additions and 16 deletions

View File

@@ -11,9 +11,14 @@ class PostReplacementsController < ApplicationController
def create
@post_replacement = authorize PostReplacement.new(creator: CurrentUser.user, post_id: params[:post_id], **permitted_attributes(PostReplacement))
@post_replacement.save
@post_replacement.process!
respond_with(@post_replacement, location: @post_replacement.post, notice: "Post replaced")
if request.format.html? && @post_replacement.errors.any?
flash[:notice] = @post_replacement.errors.full_messages.join("; ")
redirect_to @post_replacement.post
else
flash[:notice] = "Post replaced"
respond_with(@post_replacement, location: @post_replacement.post)
end
end
def update