Simplify copying files in Active Storage migration

We can use the `ActiveStorage::Blob` class to find where the file is
supposed to be stored instead of manually setting the path. This is also
more robust because it works with Active Storage configurations which
don't store files in the default folder.
This commit is contained in:
Javi Martín
2021-07-26 23:39:08 +02:00
parent 619d402f92
commit a6025d3a12

View File

@@ -61,16 +61,11 @@ namespace :active_storage do
end
ActiveStorage::Attachment.find_each do |attachment|
dest = ActiveStorage::Blob.service.path_for(attachment.blob.key)
name = attachment.name
source = attachment.record.send(name).path
dest_dir = File.join(
"storage",
attachment.blob.key.first(2),
attachment.blob.key.first(4).last(2))
dest = File.join(dest_dir, attachment.blob.key)
FileUtils.mkdir_p(dest_dir)
FileUtils.mkdir_p(File.dirname(dest))
logger.info "Copying #{source} to #{dest}"
FileUtils.cp(source, dest)
end