From 3d11aa86cef427e57384adefc2539023644440e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Tue, 13 May 2025 16:31:49 +0200 Subject: [PATCH] Fix ActiveStorage::IntegrityError when attaching PDFs This is an error we've only been able to reproduce on one specific machine and only when using the development environment. It looks like Rails 7.1.5.1 uses `ActiveStorage::PreviewImageJob` when we attach a PDF. However, that raises an IntegrityError because we're removing the metadata from PDFs. That is, the final PDF is no longer the same PDF that was uploaded. This issue wasn't present in the original Rails 7.1.0 release, but was introduced in Rails 7.1.4 [1] and has already been fixed in Rails 7.2.0 [2]. So we're applying the same solution that was applied in Rails 7.2.0: disabling automatic previews for PDFs when no variants require them by changing a method in `ActiveStorage::Attachment`. [1] See commit 6f729dd39 in https://github.com/rails/rails/ [2] See pull request 51351 in https://github.com/rails/rails/ --- .rubocop.yml | 1 + ...isable_active_storage_pdf_auto_previews.rb | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 config/initializers/disable_active_storage_pdf_auto_previews.rb diff --git a/.rubocop.yml b/.rubocop.yml index 3461640c3..2007b91dc 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -12,6 +12,7 @@ AllCops: Exclude: - "db/schema.rb" - "app/lib/ckeditor/backend/active_storage.rb" + - "config/initializers/disable_active_storage_pdf_auto_previews.rb" - "vendor/**/*" DisabledByDefault: true diff --git a/config/initializers/disable_active_storage_pdf_auto_previews.rb b/config/initializers/disable_active_storage_pdf_auto_previews.rb new file mode 100644 index 000000000..019b9fba8 --- /dev/null +++ b/config/initializers/disable_active_storage_pdf_auto_previews.rb @@ -0,0 +1,22 @@ +ActiveSupport.on_load(:active_storage_attachment) do + # Code copied from Rails 7.2. TODO: remove after upgrading to Rails 7.2 + # See: https://github.com/rails/rails/pull/51351/files + class ActiveStorage::Attachment + private + def transform_variants_later + preprocessed_variations = named_variants.filter_map { |_name, named_variant| + if named_variant.preprocessed?(record) + named_variant.transformations + end + } + + if blob.preview_image_needed_before_processing_variants? && preprocessed_variations.any? + blob.create_preview_image_later(preprocessed_variations) + else + preprocessed_variations.each do |transformations| + blob.preprocessed(transformations) + end + end + end + end +end