2012-11-12 43 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