重启后Carrierwave重置

时间:2013-03-22 18:44:18

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

app和db(mongodb)服务器昨晚都重启了。即使文件仍然存在,所有载波装载的上载器都会返回头像的默认图像。

我在Rackspace CDN上使用雾存储。每个用户模型都包含avatar_filename字段。我尝试运行user.avatar.recreate_versions!,但由于nil而导致错误。

有没有办法恢复我的图像(它们仍然存在!)并防止再次发生这种情况?我已经四处寻找,但看起来这不是一个普通的舞会。

在我的用户模型中:

# Avatar
mount_uploader :avatar, AvatarUploader

AvatarUploader:

class AvatarUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  storage :fog

  def default_url
    "/assets/users/profile-default_#{version_name}.png"
  end

  # Large
  version :large do
    resize_to_limit(600, 600)
  end

  # Small
  version :small do
    process :crop
    resize_to_fill(140, 140)
  end

  # Thumbnail
  version :thumb, :from_version => :small do
    resize_to_fill(35, 35)
  end

  def extension_white_list
    %w(jpg jpeg png)
  end

  def filename
    if @filename_created
      @filename_created
    elsif original_filename
      @name ||= Digest::MD5.hexdigest(File.dirname(current_path))
      @filename_created = "a_#{timestamp}_#{@name}.#{file.extension}"
      @filename_created
    end
  end

  def timestamp
    var = :"@#{mounted_as}_timestamp"
    model.instance_variable_get(var) or model.instance_variable_set(var, Time.now.to_i)
  end

  def crop
    if model.crop_x.present?
      resize_to_limit(600, 600)
      manipulate! do |img|
        x = model.crop_x.to_i
        y = model.crop_y.to_i
        w = model.crop_w.to_i
        h = model.crop_h.to_i
        img.crop!(x, y, w, h)
      end
    end
  end
end

1 个答案:

答案 0 :(得分:1)

鉴于图像在那里,您可以将它们重新上传为具有user.remote_avatar_url = "the url for this avatar"

的远程文件

为避免将来出现这种情况,您必须牢记如何处理文件名。每次执行recreate_versions!时都会重新应用该过程。将此代码放在您的上传器中以解决此问题:

class AvatarUploader < CarrierWave::Uploader::Base
  def filename
    if original_filename
      if model && model.read_attribute(:avatar).present?
        model.read_attribute(:avatar)
      else
        # new filename
      end
    end
  end
end

您可以在以下Wiki文章中找到有关此内容的更多信息:https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Create-random-and-unique-filenames-for-all-versioned-files