我正在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)。
我遗漏了什么?
富足
解决方法
我的变通方法是执行以下操作,但每次更新模型时运行编码例程似乎是一种耻辱:
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发布于 2012-04-26 16:04:51
我的变通方法是执行以下操作,但每次更新模型时运行编码例程似乎是一种耻辱:
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
endhttps://stackoverflow.com/questions/7041760
复制相似问题