Validate Attachment Content Type Paperclip

后端 未结 4 833
生来不讨喜
生来不讨喜 2021-01-06 03:12

Is it possible to enforce a \'content type\' validation in paperclip without enforcing a \'presence\' validation (i.e. allow blanks)? I currently have:

class         


        
4条回答
  •  时光说笑
    2021-01-06 03:46

    Working example

    In the following model only image/png, image/gif and image/jpeg are valid content types for the image attachment.

    class Photo
      has_attached_file :image
      validates_attachment_content_type :image, 
                                        :content_type => /^image\/(png|gif|jpeg)/
    end
    

    Specs

    describe Photo do
      it { should validate_attachment_content_type(:image).  
                  allowing('image/png', 'image/gif', 'image/jpeg').      
                  rejecting('text/plain', 'text/xml', 'image/abc', 'some_image/png') }
    end
    

    More info

    You could also take a look at the AttachmentContentTypeValidator class with is responsible for doing the validation.

    Or take a look at its tests which contain more examples.

提交回复
热议问题