2012-11-12 42 views
0

我試圖根據我的多態關聯類型創建動態存儲桶名稱。動態生成S3的存儲桶名稱

我的第一種方法是想這樣的事情:

class PostImage < ActiveRecord::Base 
    belongs_to :imageable, :polymorphic => true 

    has_attached_file :image, :styles => { :small => "200x200>", :thumb => "50x50>" }, 
          :storage => :s3, 
          :s3_credentials => "#{Rails.root}/config/s3.yml", 
          :path => "/:style/:id/:filename", 
          :bucket => self.imageable_type.to_s 

end 

如果我嘗試創建一個新的對象我得到了一個錯誤:

NoMethodError: undefined method `imageable_type' for #< Class:0x007fd3fe0b15d8

我找出S3文件上這樣的:

​​

問題是,我沒有得到如何我能得到這個工作,以設置我的polymorphi的名稱c關聯作爲存儲桶的名稱。

任何幫助將不勝感激。

回答

0

希望它能幫助別人,

最終的解決方案是基於這篇文章:rails paperclip S3 with dynamic bucket name

閱讀職位獲得如何使用PROC一個更好的解釋。

最終代碼:

class PostImage < ActiveRecord::Base 
    belongs_to :imageable, :polymorphic => true 

    has_attached_file :image, :styles => { 
        :square=> "170x170#", 
        :rectangle=> "220x170#", 
        :large => "600x400#" }, :storage => :s3, :s3_credentials => "#{Rails.root}/config/s3.yml", 
        :path => "/:style/:id/:filename", 
        :bucket => lambda { |attachment| "#{attachment.instance.imageable_type.to_s.downcase}-gallery" } 


end