ruby-on-rails – Carrierwave在模型更新后不会重新创建版本

我在Carrierwave Uploader上引入了一个新版本.当我创建一个新事件时,它会正确创建两个版本.但是当我更新它时,只有我附加的文件被上传,但版本不会被重新创建.

我正在使用CarrierWave 1.2.2,并查看更改日志,它似乎不是一个在较新版本中修复的错误

class CoverUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  if Rails.env.development? || Rails.env.test?
    storage :file
  elsif Rails.env.production?
    storage :fog
  end

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    if ENV['HEROKU_APP_NAME'].to_s.include?('-pr-')
      "review_apps/#{model.class.to_s.underscore}/#{model.id}"
    else
      "#{Rails.env}/#{model.class.to_s.underscore}/#{model.id}"
    end
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  def default_url(*args)
    ActionController::Base.helpers.asset_path('test.jpg')
  end

  # Create different versions of your uploaded files:
  version :optimised do
    process convert: 'webp'
    process :set_content_type_to_webp

    def full_filename(_for_file = model.cover.file)
      "cover_#{model.id}.webp"
    end

    def exists?
      file&.exists?
    end
  end

  def extension_blacklist
    %w(webp)
  end

  private

  # Required to actually force Amazon S3 to treat it like an image
  def set_content_type_to_webp
    file.instance_variable_set(:@content_type, 'image/webp')
  end
end

最佳答案 当@ogelacinyc在full_filename中找到bug时,部分是正确的.我回去测试正常功能,创建另一个版本,只需更改一个维度.然后我可以看到更新会自行重新创建版本,就像我预期的那样.

这让我觉得我的版本可能有问题:优化块.因此,在逐一评论之后,我发现full_filename是罪魁祸首.它可能是model.cover.file无声地失败,但我认为它是model.id,可以在filename method in Carrierwave的描述中看到

所以相反,我直接获取文件名,提取扩展名并用webp替换它:

  def full_filename(for_file = model.file_name.file)
    extension = File.extname(for_file)
    "cover_#{for_file.sub(extension, '.webp')}"
  end

哪个工作没有问题!

点赞