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

@@ -3,9 +3,11 @@
class PostReplacement < ApplicationRecord
belongs_to :post
belongs_to :creator, class_name: "User"
before_validation :initialize_fields, on: :create
attr_accessor :replacement_file, :final_source, :tags
before_validation :initialize_fields, on: :create
before_create :process!
attr_accessor :replacement_file, :final_source, :tags
attribute :replacement_url, default: ""
def initialize_fields