我正在使用Rails中的Paperclip保存图像上传,目前工作正常。
has_attached_file :image, :styles => {
:small => "80x90#"
}
我会在创建模型时,将小图片的一份副本保存为base64编码字符串。
before_update :encode_image
private
def encode_image
self.base64 = ActiveSupport::Base64.encode64(open(self.image.path(:small)).to_a.join)
end
上面的代码在更新时处理已保存的图像时效果很好。我想将此逻辑应用于模型保存之前但在图像被处理后触发的回调函数。
我原以为
after_post_process
会是我的救星,但此时路径尚未完全形成(缺少id)。我漏掉了什么?
Rich
解决方法:
我的解决方法是执行以下操作,但每次更新模型时都运行编码程序似乎有些可惜。
after_save :encode_image
private
def encode_image
unless self.image.path(:small).blank?
b64 = ActiveSupport::Base64.encode64(open(self.image.path(:small)).to_a.join)
unless self.base64 == b64
self.update_attribute :base64, b64
end
end
end