出于各种原因,我将上传内容从 ActiveStorage (AS) 迁移到 CarrierWave (CW)。
我正在执行 rake 任务并理清逻辑 - 我对如何将 AS blob 输入 CW 文件感到困惑。
我正在尝试类似的事情:
@files.each.with_index(1) do | a, index |
if a.attachment.attached?
a.attachment.download do |file|
a.file = file
end
a.save!
end
end
这是基于以下两个链接:
https://edgeguides.rubyonrails.org/active_storage_overview.html#downloading-files
message.video.open do |file|
system '/path/to/virus/scanner', file.path
# ...
end
和
https://github.com/carrierwaveuploader/carrierwave#activerecord
# like this
File.open('somewhere') do |f|
u.avatar = f
end
我在本地测试了这个,文件没有通过上传器挂载。我的问题是:
奖励业力问题:
最佳答案
这是我的最终机架任务(基于接受的答案)- 可以进行调整。是否适合我:
namespace :carrierwave do
desc "Import the old AS files into CW"
task import: :environment do
@files = Attachment.all
puts "#{@files.count} files to be processed"
puts "+" * 50
@files.each.with_index(1) do | a, index |
if a.attachment.attached?
puts "Attachment #{index}: Key: #{a.attachment.blob.key} ID: #{a.id} Filename: #{a.attachment.blob.filename}"
class FileIO < StringIO
def initialize(stream, filename)
super(stream)
@original_filename = filename
end
attr_reader :original_filename
end
a.attachment.download do |file|
a.file = FileIO.new(file, a.attachment.blob.filename.to_s)
end
a.save!
puts "-" * 50
end
end
end
desc "Purge the old AS files"
task purge: :environment do
@files = Attachment.all
puts "#{@files.count} files to be processed"
puts "+" * 50
@files.each.with_index(1) do | a, index |
if a.attachment.attached?
puts "Attachment #{index}: Key: #{a.attachment.blob.key} ID: #{a.id} Filename: #{a.attachment.blob.filename}"
a.attachment.purge
puts "-" * 50
@count = index
end
end
puts "#{@count} files purged"
end
end
现在,在我的情况下,我正在逐步执行此操作 - 我已经使用此 rake 任务和相关联的 MCV 更新分支了我的 master。如果我的站点处于真正的生产状态,可能会先运行导入 rake 任务,然后确认一切顺利,然后清除旧的 AS 文件。
关于ruby-on-rails - 将上传的文件从 Active Storage 迁移到 Carrierwave,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58126256/