繁体   English   中英

具有载波的相同型号的动态存储目录

[英]Dynamic store dirs for same models with carrierwave

我在雾中使用CarrierWave将图像上传到S3。

我有模型图像,可以表示不同大小的图像,并根据需要将其保存在不同的文件夹中。

例如,对于image.jpg我可以有两个不同的上载版本,需要另存为:

'images/large/image.jpg'
'images/small/image.jpg'

可能有任意数量的用例,使用minimagick的版本无法涵盖所有​​情况。

到目前为止,我还没有找到解决方案。 有谁知道如何做到这一点?

我已经问过几次这个问题,所以我将写出最终的解决方案。

我没有在模型上定义mount_uploader,而是决定独立使用Uploader,然后将url保存到记录中。

动态更改store_dir和文件名可以像这样完成

uploader = Uploader.new

uploader.define_singleton_method(:store_dir) do
    'new_store_dir'
end
uploader.define_singleton_method(:filename) do
    'new_filename'
end

uploader.store!(image)

使用这种方法,您还可以使用局部变量或控制器中可用的名称定义名称。

希望它也可以帮助其他人。

为了更改上传文件的放置位置,只需重写store_dir方法:(针对您的情况)( 参考链接

class Image < CarrierWave::Uploader::Base
storage :file
  # this if you using use condition for folder location
  def store_dir
    if model.somefield == "somecondition
       "uploads/#{model.somefield}"
    elsif model.somefield == "somecondition
       "uploads/location2"
    else
       "uploads/default_dir"
    end

  end
  # this is if you want to use version_name
  def store_dir
    'images/#{version_name}/'
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM