Rails Paperclip多态风格

Ran*_*uin 5 ruby-on-rails paperclip

我正在使用paperclip为使用accepts_nested_attributes_for的多个模型的附件.有没有办法为每个模型指定特定的回形针样式选项?

Eri*_*ric 10

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

# 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
Run Code Online (Sandbox Code Playgroud)

它们都进入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
Run Code Online (Sandbox Code Playgroud)

最后,由于您确实拥有资产模型,因此您仍然可以直接从中读取,例如,如果您需要20个最新资产的列表.此外,此示例不限于分离媒体类型,它也可以用于不同类型的同一事物:头像<资产,图库<资产等.

  • 您在哪里定义文件的保存位置?在资产模型?或者资产模型是空白的吗?说:`:storage =>:s3,:bucket => Rails.application.config.aws_s3_bucket,:s3_credentials =>"#{Rails.root} /config/s3.yml",:path =>":class /: ID /:款式/:基本名称:扩展名"` (2认同)