use*_*095 1 ruby-on-rails rails-migrations carrierwave rails-activestorage
我有一个使用Carrierwave来处理文件上传的应用程序,但确实喜欢ActiveStorage的简单性。在以前的日落开发中,有很多关于从Paperclip迁移到ActiveStorage的教程,但是从Carrierwave迁移到ActiveStorage方面我看不到任何东西。有没有人成功完成了迁移,并且可以指出正确的方向?
小智 5
程序实际上确实很简单。
配置活动存储区。尝试使用与载波不同的存储桶
配置模型以便提供对ActiveStorage的访问。例
class Photo < AR::Base
mount_uploader :file, FileUploader # this is the current carrierwave implementation. Don't remove it
has_one_attached :file_new # this will be your new file
end
Run Code Online (Sandbox Code Playgroud)
现在,您将具有相同模型的两个实现。的载波访问file和的ActiveStoragefile_new
从Carrierwave下载图像并将其保存到活动存储区。这可以在rake文件,activeJob等文件中实现。
Photo.find_each do |photo|
begin
filename = File.basename(URI.parse(photo.fileurl))
photo.file_new.attach(io: open(photo.file.url), filename: d.file )
rescue => e
## log/handle your errors in order to retry later
end
end
Run Code Online (Sandbox Code Playgroud)
此时,您在载波存储桶上将有一张图像,而在活动存储桶上将有新创建的图像!
准备好迁移后,请修改模型,更改活动存储访问器并删除载波集成
class Photo < AR::Base
has_one_attached :file # we changed the atachment name from file_new to file
end
Run Code Online (Sandbox Code Playgroud)
这是一个方便的选项,因此您在控制器和其他地方的集成保持不变。希望!
更新active_storage_attachments表上的记录,以便找到附件,file而不是将file_new列name从“ file_new” 更新为“ file”
可以对应用程序进行其他一些调整以处理要考虑的问题
这样的东西在一个助手中:
photo.attached? ? url_for(photo.file_new) : photo.file.url
我希望这有帮助!
| 归档时间: |
|
| 查看次数: |
1322 次 |
| 最近记录: |