2016-01-20 35 views
0

我有一個使用Paperclip並將圖像保存到S3的Rails應用程序。當用戶上傳沒有圖像的資源時,它將獲取在回形針設置中設置的默認圖像。在Rails模型中獲取公共資產的URL

我的API提供這些資源,並且鏈接到JSON響應中的圖像(使用jbuilder),但是我似乎無法返回默認圖像URL,它只返回「missing.png」,我希望它將完整的URL返回給服務器並附上缺少的圖像路徑。

我在模型中設置了默認的URL,我嘗試過使用ActionView :: Helpers :: AssetUrlHelper來獲取image_url,但它永遠不會工作,即使它在rails控制檯內工作。任何想法我可以做什麼來解決它?

的JBuilder的文件:

json.profile_picture_smallest asset.profile_picture.url(:smallest) 
json.profile_picture_small asset.profile_picture.url(:small) 
json.profile_picture_medium asset.profile_picture.url(:medium) 
json.profile_picture_large asset.profile_picture.url(:large) 
json.profile_picture_original asset.profile_picture.url(:original) 

包含在模型

module Picturable 
    extend ActiveSupport::Concern 

    included do 
     has_attached_file :profile_picture, path: '/images/' + name.downcase.pluralize + '/:style/:basename', default_url: "missing.png", 
     styles: { 
     smallest: '50x50>', 
     small: '100x100>', 
     medium: '200x200>', 
     large: '400x400>', 
     png: ['400x400>',:png] 
     }, :convert_options => { 
     smallest: '-trim', 
     small: '-trim', 
     medium: '-trim', 
     large: '-trim', 
     png: '-trim' 
     } 



     # Validate the attached image is image/jpg, image/png, etc 
     validates_attachment_content_type :profile_picture, :content_type => /\Aimage\/.*\Z/ 
    end 

    def set_uuid_name 
     begin 
     self.profile_picture_file_name = SecureRandom.uuid 
     end while self.class.find_by(:profile_picture_file_name => self.profile_picture_file_name) 
    end 
end 

回形針配置紙夾的一部分:

Paperclip::Attachment.default_options[:s3_host_name] = 's3hostname' 

開發配置:

config.paperclip_defaults = { 
    :storage => :s3, 
     :s3_credentials => { 
     :bucket => 'paperclipdev', 
     :access_key_id => 'accesskey', 
     :secret_access_key => 'secretaccesskey' 
    } 
    } 
+0

請包括相關的代碼:jbuilder視圖,你的Paperclip配置等 – max

+0

這樣做的一種方式是上傳s3中的'missing.png'並使用它的url作爲圖像的默認值,因爲你已經在使用s3用於其他文件。 –

+0

我更新了問題。我意識到這是一種方式,但我寧願將它們留在軌道中,有沒有辦法? – brunoban

回答

0

我認爲要做到這一點的方法是使用資產傭工在JBuilder的文件:

json.profile_picture_smallest asset_url(asset.profile_picture.url(:smallest)) 

值得一提的這裏,你還可以傳遞一個符號方法名回形針因爲如果你的default_url參數希望基於模型的默認網址是動態的。

相關問題