Rails 4、Paperclip on Heroku 无法识别损坏的图像

Rails 4, Paperclip on Heroku does not recognize broken image

无法解决我项目中的图片问题。

总结:Rilas 4 托管在 Heroku 上,使用带 S3 的 Paerclip

问题始于必须使用以前在 S3 中使用的自定义上传逻辑。图片 url 看起来像这样 /profile_picture/:style_:image_hash。它适用于存在的图像但不存在的图像回形针仍在尝试访问不存在的图像并且实际的 link 看起来像这样:http://s3.amazonaws.com/project/profile_pictures/100h_.

 has_attached_file :picture,
                styles:          { :'53h' => '', :'100h' => '' },
                convert_options: {
                    :'100h' => '-gravity center -thumbnail 165x165^ -extent 165x165',
                    :'53h'  => '-gravity center -thumbnail 45x45^ -extent 45x45'
                },
                path:            'profile_pictures/:style_:filename',
                default_url:     '/images/default-pp-large.jpg'

我猜这可能是因为实际文件名中的样式,但我不确定,总的来说 defauly_url 不起作用,图像全部损坏,不包括实际存在的图像。

你能帮忙吗?

我想知道 ID 怎么没有出现在图片的路径中,因为在这种情况下,如果 2 张不同的图片具有相同的名称,它将检索第一个匹配项,正如我认为的那样,路径应该是这样的:

path: 'profile_pictures/:id_:style_:filename'
# OR
path: 'profile_pictures/:id/:style_:filename'

不确定这是否应该完全解决问题,但这是其中的一部分。

最后我给回形针做了一个猴子包gem。将此行添加到 config/initializers/paperclip.rb

module Paperclip
  class Attachment
    alias_method :original_url, :url

    def url(style_name = default_style, options = {})
      if @instance.public_send("#{@name.to_s}_file_name").blank?
        'default-pp-large.jpg'
      else
        original_url(style_name, options)
      end
    end
  end
end