Ignore missing records in Active Storage migration

There could be inconsistencies in the database and an attachment might
have a `record_id` pointing to a record which no longer exist. We were
getting an exception in this case.
This commit is contained in:
Javi Martín
2021-07-27 01:29:03 +02:00
parent fd67477281
commit b5026e12a7
2 changed files with 14 additions and 1 deletions

View File

@@ -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

View File

@@ -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