PaperTrail对Carrierwave和`remove_previously_stored_files_after_update`选项不起作用

时间:2015-04-14 09:50:37

标签: ruby-on-rails carrierwave paper-trail-gem

我需要为我的Rails应用程序版本化图像。我使用Carrierwave进行文件上传,使用PaperTrail进行版本控制。

虽然版本控制似乎运行良好,但似乎启用版本并不能很好地解决Carrierwave的remove_previously_stored_files_after_update配置停用:在这种情况下,简单reload已知的模型实例不再起作用,只有来自数据库的明确新负载(使用Model.find 123)才有效。

我创建了一个demo Rails app来证明问题。

User模型会安装两个上传者:

  • AvatarUploader,在更新后删除文件(默认)
  • KeepingFilesAvatarUploader,使用设置为remove_previously_stored_files_after_update
  • false选项,在更新后无法删除文件

AvatarUploader代码:

# encoding: utf-8

class AvatarUploader < CarrierWave::Uploader::Base
  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{model.id}/#{mounted_as}"
  end
end

KeepingFilesAvatarUploader代码:

# encoding: utf-8

class KeepingFilesAvatarUploader < CarrierWave::Uploader::Base
  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{model.id}/#{mounted_as}"
  end

  configure do |config|
    config.remove_previously_stored_files_after_update = false
  end
end

唯一的区别是remove_previously_stored_files_after_update选项。

以下是User型号的代码:

class User < ActiveRecord::Base
  has_paper_trail only: [:name, :avatar, :keeping_files_avatar]
  mount_uploader :avatar, AvatarUploader
  mount_uploader :keeping_files_avatar, KeepingFilesAvatarUploader
end

我写了一些证明这种意外行为的规格。由于发布时间有点长,请看这里:

https://github.com/jmuheim/test-carrierwave-papertrail/blob/master/spec/models/user_spec.rb#L20

除了我设置为pending的规格外,所有规格都通过了,输出是

  1) User versioning reloading the model after reify sets "keeping_files_avatar" to the original value
     # See http://stackoverflow.com/questions/29624223/papertrail-doesnt-play-nice-with-carrierwave-and-remove-previously-stored-file
     Failure/Error: expect(user.keeping_files_avatar.file.filename).to eq 'original-image.jpg' # This upload field isn'! <<<FAILING LINE>>>!

       expected: "original-image.jpg"
            got: "new-image.jpg"

       (compared using ==)
     # ./spec/models/user_spec.rb:20:in `block (4 levels) in <top (required)>'

Finished in 0.20704 seconds (files took 1.51 seconds to load)
4 examples, 0 failures, 1 pending

让这个工作真的很棒。我现在不需要这项功能,但我不想为我的项目增加任何技术债务(特别是这可能导致非常不可预见的问题,因为人们通常只依赖于{{1}在模型上刷新其属性)。

1 个答案:

答案 0 :(得分:0)

检查这是否适合您

class User < ActiveRecord::Base
  has_paper_trail only: [:name, :avatar, :keeping_files_avatar]

  mount_uploader :avatar, AvatarUploader
  mount_uploader :keeping_files_avatar, KeepingFilesAvatarUploader

  skip_callback :save, :after, :remove_previously_stored_keeping_files_avatar
end