背景
我正在使用文件系统存储,其Shrine :: Attachment模块处于model设置(my_model),具有activerecord(Rails)。我也在直接上传的情况下使用它,因此我需要文件上传的响应(保存到缓存)。
my_model.rb
class MyModel < ApplicationRecord
include ImageUploader::Attachment(:image) # adds an `image` virtual attribute
omitted relations & code...
end
my_controller.rb
def create
@my_model = MyModel.new(my_model_params)
# currently creating derivatives & persisting all in one go
@my_model.image_derivatives! if @my_model.image
if @my_model.save
render json: { success: "MyModel created successfully!" }
else
@errors = @my_model.errors.messages
render 'errors', status: :unprocessable_entity
end
目标
理想情况下,我想只将当前在我的create控制器中拥有的缓存文件(派生文件和原始文件)持久保存到永久存储中后立即清除。
对于方案A:同步和方案B:异步,最好的方法是什么?
我考虑过/尝试过的事情
阅读文档后,我注意到清除缓存图像的3种可能方法:
1。。运行rake task清除缓存的图像。
我真的不喜欢这样,因为我认为一旦文件被持久保存就应该清除缓存文件,而不应将其作为不能用图像持久性规范进行测试的管理任务(cron作业)
# FileSystem storage
file_system = Shrine.storages[:cache]
file_system.clear! { |path| path.mtime < Time.now - 7*24*60*60 } # delete files older than 1 week
2。。在an after block
中运行Shrine.storages [:cache]这仅适用于后台作业吗?
attacher.atomic_persist do |reloaded_attacher|
# run code after attachment change check but before persistence
end
3。 Move将缓存文件保存到永久存储
我认为我不能使用它,因为直接上传发生在两个不同的部分:1,立即将附件上传到缓存的存储区,然后2,将其保存到新创建的记录。
plugin :upload_options, cache: { move: true }, store: { move: true }
是否有更好的方法可以从缓存中清除升级后的图像以满足我的需求?
答案 0 :(得分:0)
单张图片上传案例的同步解决方案:
def create
@my_model = MyModel.new(my_model_params)
image_attacher = @my_model.image_attacher
image_attacher.create_derivatives # Create different sized images
image_cache_id = image_attacher.file.id # save image cache file id as it will be lost in the next step
image_attacher.record.save(validate: true) # Promote original file to permanent storage
Shrine.storages[:cache].delete(image_cache_id) # Only clear cached image that was used to create derivatives (if other images are being processed and are cached we dont want to blow them away)
end