使用单个回形针字段来处理不同文件类型的可能性有多大。例如,我有一个带有回形针方法的文件模型,它说:
has_attached_file :file
该文件可以是图片、音频、视频或文档。
如果是图片,我怎样才能做到
has_attached_file :file
将能够以这种方式处理图片:has_attached_file :file, styles: {thumb: "72x72#"}
然后,如果它是其他文档类型,它会在没有样式的情况下正常工作,因此我不必为不同的文件类型创建字段。
最佳答案
处理条件样式的方法是使用 lambda
以确定您正在处理的内容类型。我们之前已经使用较早版本的 Rails/Paperclip 完成了此操作:
#app/models/attachment.rb
Class Attachment < ActiveRecord::Base
has_attached_file :file,
styles: lambda { |a| a.instance.is_image? ? {:small => "x200>", :medium => "x300>", :large => "x400>"} : {}}
validates_attachment_content_type :file, :content_type => [/\Aimage\/.*\Z/, /\Avideo\/.*\Z/]
private
def is_image?
attachment.instance.attachment_content_type =~ %r(image)
end
end
关于ruby-on-rails - 如何使用回形针处理多种文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23161266/