我有一个允许的文件扩展名列表
def extension_white_list
%w(pdf doc docx xls xlsx html tif gif jpg jpeg png bmp rtf txt)
end
和模型中定义的大小限制验证
mount_uploader :inv_file, InvFileUploader
validates_size_of :inv_file, maximum: 25.megabyte, message: "Attachment size exceeds the allowable limit (25 MB)."
工作正常,大小限制验证适用于所有已定义的文件扩展名。
但我想对不同的文件应用不同的大小限制,即
我怎样才能做到这一点?
答案 0 :(得分:3)
你可以这样试试
class Product < ActiveRecord::Base
mount_uploader :inv_file, InvFileUploader
validate :file_size
def file_size
extn = file.file.extension.downcase
size = file.file.size.to_f
if ["png", "jpg", "jpeg"].include?(extn) && size > 5.megabytes.to_f
errors.add(:file, "You cannot upload an image file greater than 5MB")
elsif (extn == "pdf") && size > 20.megabytes.to_f
errors.add(:file, "You cannot upload an pdf file greater than 20MB")
else
errors.add(:file, "You cannot upload a file greater than 25MB")
end
end
end