模型更新后,Carrierwave不会重新创建版本

时间:2019-02-17 18:40:17

标签: ruby-on-rails ruby ruby-on-rails-5 carrierwave

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

我正在使用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

3 个答案:

答案 0 :(得分:2)

@ogelacinyc在full_filename中发现错误时,部分正确。我回过头来测试正常功能,并创建另一个版本,并进行简单的尺寸更改。然后我可以看到更新将像预期的那样自行重新创建版本。

这使我认为version :optimised块可能存在问题。因此,在逐一评论之后,我发现是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

哪个可以正常工作!

答案 1 :(得分:0)

您需要向事件添加after_save回调,然后在已安装的上传器上调用recreate_versions!

假设您有一个具有以下内容的事件模型,这将解决您的问题。

class Event < ApplicationRecord
  mount_uploader :cover_image, CoverUploader
  after_save :recreate_versions!
  delegate :recreate_versions!, to: :cover_image, allow_nil: true
end

另请参见CarrierWave's README

答案 2 :(得分:-1)

我已经测试了您的代码并找到了错误。

它无法使用full_filename方法初始化变量_for_file

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

model.cover在创建优化版本时调用错误“未定义的方法cover”。