2010-08-19 46 views
5

我使用回形针作为使用accept_nested_attributes_for的多个模型的附件。有没有一种方法可以为每个模型指定特定的回形针样式选项?Rails回形针多态样式

回答

10

是的。我在站点上使用单表继承(STI)来通过资产模型处理音频,视频和图像。

# models/Asset.rb 
class Asset < ActiveRecord::Base 
    # Asset has to exist as a model in order to provide inheritance 
    # It can't just be a table in the db like in HABTM. 
end 

# models/Audio.rb 
class Audio < Asset # !note inheritance from Asset rather than AR! 
    # I only ever need the original file 
    has_attached_file :file 
end 

# models/Video.rb 
class Video < Asset 
    has_attached_file :file, 
    :styles => { 
     :thumbnail => '180x180', 
     :ipod => ['320x480', :mp4] 
     }, 
    :processors => "video_thumbnail" 
end 

# models/Image.rb 
class Image < Asset 
    has_attached_file :file, 
    :styles => { 
     :medium => "300x300>", 
     :small => "150x150>", 
     :thumb => "40x40>", 
     :bigthumb => "60x60>" 
    } 
end 

都配到Rails为:file,但是控制器(A/V/I)知道保存到适当的模式。请记住,任何媒体形式的所有属性都需要包含在Asset中:如果视频不需要标题,但图像需要,那么标题属性将为零,如Video。它不会抱怨。

如果连接到STI模型,关联也可以正常工作。 User has_many :videos的操作与您现在使用的操作相同,只要确保不要直接保存到资产。

# controllers/images_controller.rb 
    def create 
    # params[:image][:file] ~= Image has_attached_file :file 
    @upload = current_user.images.build(params[:image]) 
    # ... 
    end 

最后,既然您确实有一个资产模型,您仍然可以直接从它读取数据,例如,你想要一个最近20个资产的列表。此外,此示例不限于分隔媒体类型,它还可用于不同类型的相同内容:阿凡达<资产,图库<资产等。

+2

你在哪里定义在文件被保存?在资产模型上?或者资产模型是空白的?说:':storage =>:s3, :bucket => Rails.application.config.aws_s3_bucket, :s3_credentials =>“#{Rails.root} /config/s3.yml”, :path =>“: class /:id /:style /:basename。:extension“' – 2012-02-26 02:37:37

+0

我只是使用默认值并将Asset模型保留为空,但我敢打赌,有一种方法可以在Asset模型中设置默认值。我没有尝试。 – Eric 2012-09-28 02:37:03

2

一个更nicer方式就可以了,(如果使用的是在处理图像):

class Image < ActiveRecord::Base 
    belongs_to :imageable, :polymorphic => true 
    has_attached_file :attachment, styles: lambda { 
    |attachment| { 
     thumb: ( 
     attachment.instance.imageable_type.eql?("Product") ? ["300>", 'jpg'] : ["200>", 'jpg'] 
    ), 
     medium: ( 
     ["500>", 'jpg'] 
    ) 
    } 
    } 
end 
+0

你的答案真的有用吗? attachment.instance.imageable_type为零 – 2013-11-09 14:12:20

+0

@ArtemAminov是的,它工作..因为我在我的项目中使用它。 – 2013-11-10 23:22:28

+0

也许你可以帮助我与我的项目,请看这里的代码[链接](http://stackoverflow.com/questions/19901485/paperclip-polymorphic-styles) – 2013-11-11 08:03:43