diff --git a/lib/tasks/active_storage.rake b/lib/tasks/active_storage.rake index bfc2fd2e0..ecf3d0388 100644 --- a/lib/tasks/active_storage.rake +++ b/lib/tasks/active_storage.rake @@ -69,7 +69,7 @@ namespace :active_storage do ActiveStorage::Attachment.find_each do |attachment| dest = ActiveStorage::Blob.service.path_for(attachment.blob.key) - next if File.exist?(dest) + next if File.exist?(dest) || !attachment.record name = attachment.name.delete_prefix("storage_") source = attachment.record.send(name).path diff --git a/spec/lib/tasks/active_storage_spec.rb b/spec/lib/tasks/active_storage_spec.rb index 359a00ecb..f554d05de 100644 --- a/spec/lib/tasks/active_storage_spec.rb +++ b/spec/lib/tasks/active_storage_spec.rb @@ -64,6 +64,19 @@ describe "active storage tasks" do expect(test_storage_file_paths.first).to eq migrated_file end + it "does not migrate files for deleted records" do + document = create(:document, attachment: File.new("spec/fixtures/files/clippy.pdf")) + FileUtils.rm storage_file_path(document) + Document.delete_all + + run_rake_task + + expect(ActiveStorage::Attachment.count).to eq 1 + expect(ActiveStorage::Blob.count).to eq 1 + expect(document.storage_attachment.filename).to eq "clippy.pdf" + expect(test_storage_file_paths.count).to eq 0 + end + def test_storage_file_paths Dir.glob("#{storage_root}/**/*").select { |file_or_folder| File.file?(file_or_folder) } end