按照@galatians 的想法,我得到了这个解决方案(并且工作得很好)
为该示例创建了一个 repo:
* https://github.com/mariohmol/paperclip-keeponvalidation
- 首先要做的就是将一些方法放入您的基本活动记录中,这样每个使用附加的模型都可以使其工作
在 config/initializers/active_record.rb 中
module ActiveRecord
class Base
def decrypt(data)
return '' unless data.present?
cipher = build_cipher(:decrypt, 'mypassword')
cipher.update(Base64.urlsafe_decode64(data).unpack('m')[0]) + cipher.final
end
def encrypt(data)
return '' unless data.present?
cipher = build_cipher(:encrypt, 'mypassword')
Base64.urlsafe_encode64([cipher.update(data) + cipher.final].pack('m'))
end
def build_cipher(type, password)
cipher = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC').send(type)
cipher.pkcs5_keyivgen(password)
cipher
end
#ex: @avatar_cache = cache_files(avatar,@avatar_cache)
def cache_files(avatar,avatar_cache)
if avatar.queued_for_write[:original]
FileUtils.cp(avatar.queued_for_write[:original].path, avatar.path(:original))
avatar_cache = encrypt(avatar.path(:original))
elsif avatar_cache.present?
File.open(decrypt(avatar_cache)) {|f| assign_attributes(avatar: f)}
end
return avatar_cache
end
end
end
- 之后,在您的模型和附加字段中包含上面的代码
例如,我将其包含在 /models/users.rb 中
has_attached_file :avatar, PaperclipUtils.config
attr_accessor :avatar_cache
def cache_images
@avatar_cache=cache_files(avatar,@avatar_cache)
end
-
在您的控制器中,添加它以从缓存中获取图像(就在您保存模型的位置之前)
@user.avatar_cache = 参数[:user][:avatar_cache]
@user.cache_images
@user.save
最后将其包含在您的视图中,以记录当前临时图像的位置
f.hidden_field :avatar_cache
- 如果您想在视图中显示实际文件,请包含它:
<% if @user.avatar.exists? %>
<label class="field">Actual Image </label>
<div class="field file-field">
<%= image_tag @user.avatar.url %>
</div>
<% end %>