Files
nairobi/app/controllers/direct_uploads_controller.rb
Javi Martín e0e35298d5 Use Active Storage to handle cached attachments
This fixes a few issues we've had for years.

First, when attaching an image and then sending a form with validation
errors, the image preview would not be rendered when the form was
displayed once again. Now it's rendered as expected.

Second, when attaching an image, removing it, and attaching a new
one, browsers were displaying the image preview of the first one. That's
because Paperclip generated the same URL from both files (as they both
had the same hash data and prefix). Browsers usually cache images and
render the cached image when getting the same URL.

Since now we're storing each image in a different Blob, the images have
different URLs and so the preview of the second one is correctly
displayed.

Finally, when users downloaded a document, they were getting files with
a very long hexadecimal hash as filename. Now they get the original
filename.
2022-02-23 18:21:38 +01:00

35 lines
1.2 KiB
Ruby

class DirectUploadsController < ApplicationController
include DirectUploadsHelper
include ActionView::Helpers::UrlHelper
before_action :authenticate_user!
skip_authorization_check only: :create
helper_method :render_destroy_upload_link
def create
@direct_upload = DirectUpload.new(direct_upload_params.merge(user: current_user, attachment: params[:attachment]))
if @direct_upload.valid?
@direct_upload.save_attachment
@direct_upload.relation.set_cached_attachment_from_attachment
render json: { cached_attachment: @direct_upload.relation.cached_attachment,
filename: @direct_upload.relation.storage_attachment.filename.to_s,
destroy_link: render_destroy_upload_link(@direct_upload),
attachment_url: polymorphic_path(@direct_upload.relation.storage_attachment) }
else
render json: { errors: @direct_upload.errors[:attachment].join(", ") },
status: :unprocessable_entity
end
end
private
def direct_upload_params
params.require(:direct_upload)
.permit(:resource, :resource_type, :resource_id, :resource_relation,
:attachment, :cached_attachment, attachment_attributes: [])
end
end