Paperclip [RoR]中同一文件的多次验证

时间:2014-04-17 04:20:31

标签: ruby-on-rails ruby

基本上我想有办法做类似的事情(这是伪代码)

if file == image
size = 2mb
else if file == audio
size = 5mb
end

我可以使用验证,因为我希望我上传的任何内容都会受到不同的限制,例如文件大小,具体取决于上传的文件类型。

https://github.com/thoughtbot/paperclip#validations

我将在下面发布我当前的模型

class Upload < ActiveRecord::Base
      has_attached_file :file, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"

      do_not_validate_attachment_file_type :file

      include Rails.application.routes.url_helpers

      def to_jq_upload
        {
          "name" => read_attribute(:file_file_name),
          "size" => read_attribute(:file_file_size),
          "url" => file.url(:original),
          "delete_url" => upload_path(self),
          "delete_type" => "DELETE"
        }
      end
    end

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这是我们之前做过的事情(不确定它是否仍适用于recent Paperclip upgrades):

#app/models/attachment.rb
Class Attachment < ActiveRecord::Base
     has_attached_file :attachment
     validates_attachment :size => Proc.new {|attachment
        if attachment.is_image?
            15mb
        elsif attachment.is_audio?
            2mb
        end
     }

     private

     def is_image?
         attachment.instance.attachment_content_type =~ %r(image)
     end

     def is_audio?
         attachment.instance.attachment_content_type =~ %r(audio)
     end

end