Files
danbooru/app/controllers/post_replacements_controller.rb
evazion 60a13fd2d5 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.
2022-02-01 01:14:41 -06:00

39 lines
1.3 KiB
Ruby

# frozen_string_literal: true
class PostReplacementsController < ApplicationController
respond_to :html, :xml, :json, :js
def new
@post_replacement = authorize PostReplacement.new(post_id: params[:post_id], **permitted_attributes(PostReplacement))
respond_with(@post_replacement)
end
def create
@post_replacement = authorize PostReplacement.new(creator: CurrentUser.user, post_id: params[:post_id], **permitted_attributes(PostReplacement))
@post_replacement.save
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
@post_replacement = authorize PostReplacement.find(params[:id])
@post_replacement.update(permitted_attributes(@post_replacement))
respond_with(@post_replacement)
end
def index
params[:search][:post_id] = params.delete(:post_id) if params.key?(:post_id)
@post_replacements = authorize PostReplacement.paginated_search(params)
@post_replacements = @post_replacements.includes(:creator, post: [:uploader, :media_asset]) if request.format.html?
respond_with(@post_replacements)
end
end