CarrierWave 在单个模型中使用一个上传器两次

CarrierWave use one uploader two times in single model

我有一个名为 User 的模型。它有两个字段:small_logobig_logo。 这些实际上是不同张图片,而不仅仅是一张调整大小的图片。

class User < ActiveRecord::Base
  ...
    mount_uploader :big_logo, UserLogoUploader
    mount_uploader :small_logo, UserLogoUploader
  ...
end

我用UserLogoUploader上传这张图片

而且我 运行 遇到了一个错误 - 只要模型名称相同,上传的文件就会获得相同的路径,所以如果我尝试上传两个具有相同名称的不同文件 -第二个覆盖第一个。

显而易见的解决方案是为这些字段使用不同的上传器。但是我不想创建另一个上传器来修复这个错误——我能做些什么来修改文件名,例如,用一些有意义的东西,比如提交这个文件的表单字段的名称或模型字段的访问名称正在处理中。

经过一些搜索找到了我自己的问题的答案

上传器中有一个 mounted_as 属性,参考文档,它完全符合我的需要:

If a model is given as the first parameter, it will stored in the uploader, and
available throught +#model+. Likewise, mounted_as stores the name of the column
where this instance of the uploader is mounted. These values can then be used inside
your uploader.

所以整个解决方案如下所示:

def UserLogoUploader < CarrierWave::Uploader::Base
  ...
  def store_dir
    File.join [
      Settings.carrierwave.store_dir_prefix,
      model.class.to_s.underscore,
      mounted_as.to_s,
      model.id.to_s
    ].select(&:present?)
  end
  ...
end

此代码为不同的模型字段创建不同的子文件夹,这有助于防止名称重复和文件覆盖。