Validate Attachment Content Type Paperclip

*爱你&永不变心* 提交于 2019-11-30 17:12:44

问题


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

class Person < ActiveRecord::Base
  has_attached_file :picture
  validates_attachment_content_type :picture, :content_type => ['image/jpeg', 'image/jpg', 'image/png']
end

However, this fails if no attachment is present. For example:

>> @person = Person.new
>> @person.save
>> @person.errors.first
=> ["picture_content_type", "is not one of image/jpeg, image/jpg, image/png"]

Is it possible to do the validation only if an attachment is included.


回答1:


I'm not sure that method is the cause of your failure; Here's my simple class

class Image < ActiveRecord::Base
  has_attached_file :photo, {
            :styles => { :large => "700x400#", :medium=>"490x368#", :thumbnail=>"75x75#" },
            :default_url => "/images/thumbnail/blank-recipe.png"}
  validates_attachment_content_type :photo, :content_type => /image/ 
end

Then, if I:

Image.new.valid?
#this is true

You might be doing other paperclip validations, though. Can you post a simple example?




回答2:


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.




回答3:


validates_content_type accepts :if => Proc.new{|r| !r.content_type.blank?} in it's options hash, perhaps that would solve your problem.

http://rdoc.info/github/thoughtbot/paperclip#




回答4:


This worked for me;

validates_attachment :image1, :presence => true,
                         :content_type => { :content_type => "image/jpg" },
                         :size => { :in => 0..10.kilobytes }


来源:https://stackoverflow.com/questions/3181845/validate-attachment-content-type-paperclip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!