Rails - 使用SQL获取Paperclip URL

时间:2015-04-17 15:24:05

标签: ruby-on-rails paperclip

我有一个电子商务应用。我用paperclip上传图片。在我的视图页面中,我使用@product.image.url(:thumb)作为缩略图,@product.image.url作为缩放图像。

如果我想在产品表上使用SQL并获取所有网址(拇指和完整尺寸)的列表,我该怎么办? Paperclip会在表格中存储一些图片信息,但不会存储网址,因此我不知道要使用哪个字段。

1 个答案:

答案 0 :(得分:0)

您需要使用回形针一样的方式来构造URL。这是每个项目的自定义。您的SQL Server可能还需要执行哈希和时间转换。

您可以在Paperclip::AttachmentPaperclip::Interpolations以及Paperclip::Storage中的某个模块中找到相关代码。

我没有SQL示例,但是Ruby中仅使用实体并且不依赖Paperclip的解决方案可能看起来像这样:

entity = User.first
entity_plural_name = "users"
attachment_plural_name = "pictures"

storage = "https://myapp.s3.amazonaws.com/"
secret = "somer4nd0mhash"

styles = [:min, :max, :original]
styles.each_with_object({}) do |style, aggregator|
  hash = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, "#{entity_plural_name}/#{attachment_plural_name}/#{entity.id}/#{style}/#{entity.picture_updated_at.to_i}")
  aggregator[style] = "#{storage}/#{entity_plural_name}/#{style}/#{hash}.jpg"
end

使用paperclip 6.1.0