Rails Paperclip多态样式

5

我正在使用Paperclip为多个模型的附件使用accepts_nested_attributes_for。我是否可以为每个模型指定特定的Paperclip样式选项?

2个回答

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

它们全部以 :file 的形式进入Rails,但控制器(A/V/I)知道要保存到适当的模型中。只需记住,所有形式的媒体的属性都需要包含在 Asset 中:如果视频不需要字幕,但图像需要,则对于 Video,字幕属性将为nil。这不会报错。

如果连接到STI模型,关联也将正常工作。 User has_many :videos 将与您现在使用的方式相同,只需确保不要尝试直接保存到 Asset

  # 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" - Victor S
我只是使用默认设置并保持资产模型为空白,但我敢打赌在资产模型中有一种设置默认值的方法。我还没有尝试过。 - Eric

2

如果您正在处理图像,一种更好的方法是:

这里有一个非常好的例子。

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

你的回答真的有效吗?attachment.instance.imageable_type是nil。 - Artem Aminov
@ArtemAminov 是的,它有效...因为我正在我的一个项目中使用它。 - Mohit Jain
也许你可以帮我完成我的项目,请查看这里的代码链接 - Artem Aminov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接