Don't migrate files already in Active Storage

This way we reduce the hypothetical problems we could find if executing
the task several times.
This commit is contained in:
Javi Martín
2021-07-27 01:18:57 +02:00
parent 7330bfb6ae
commit fd67477281
2 changed files with 25 additions and 0 deletions

View File

@@ -40,6 +40,8 @@ namespace :active_storage do
model.find_each.each do |instance| model.find_each.each do |instance|
attachments.each do |attachment| attachments.each do |attachment|
next if instance.send(:"storage_#{attachment}").attached?
source = instance.send(attachment).path source = instance.send(attachment).path
next if source.blank? next if source.blank?
@@ -66,6 +68,9 @@ namespace :active_storage do
ActiveStorage::Attachment.find_each do |attachment| ActiveStorage::Attachment.find_each do |attachment|
dest = ActiveStorage::Blob.service.path_for(attachment.blob.key) dest = ActiveStorage::Blob.service.path_for(attachment.blob.key)
next if File.exist?(dest)
name = attachment.name.delete_prefix("storage_") name = attachment.name.delete_prefix("storage_")
source = attachment.record.send(name).path source = attachment.record.send(name).path

View File

@@ -44,6 +44,26 @@ describe "active storage tasks" do
expect(test_storage_file_paths.count).to eq 0 expect(test_storage_file_paths.count).to eq 0
end end
it "does not migrate already migrated records" do
document = create(:document, attachment: File.new("spec/fixtures/files/clippy.pdf"))
migrated_file = test_storage_file_paths.first
attachment_id = document.storage_attachment.attachment.id
blob_id = document.storage_attachment.blob.id
run_rake_task
document.reload
expect(ActiveStorage::Attachment.count).to eq 1
expect(ActiveStorage::Blob.count).to eq 1
expect(document.storage_attachment.attachment.id).to eq attachment_id
expect(document.storage_attachment.blob.id).to eq blob_id
expect(test_storage_file_paths.count).to eq 1
expect(storage_file_path(document)).to eq migrated_file
expect(test_storage_file_paths.first).to eq migrated_file
end
def test_storage_file_paths def test_storage_file_paths
Dir.glob("#{storage_root}/**/*").select { |file_or_folder| File.file?(file_or_folder) } Dir.glob("#{storage_root}/**/*").select { |file_or_folder| File.file?(file_or_folder) }
end end