繁体   English   中英

Rails Paperclip多态风格

[英]Rails Paperclip polymorphic styles

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

是。 我在站点上使用单表继承(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

它们都进入Rails as :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个最近资产的列表。 此外,此示例不限于分离媒体类型,它也可以用于不同类型的同一事物:头像<资产,图库<资产等。

一个更好的方法可以是(如果使用处理图像):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM