问题
I am using the following way to validate the mime type of uploaded file content with carrier wave.
https://gist.github.com/denyago/1298417
But this validation is running all the time even when no content is uploaded. This obviously fails as there is nothing to validate.
validates :logo, :file_mime_type => {:content_type => /image/}
Is there any work around to skip validation when no content is uploaded?
Thanks !!
UPDATE:
Using the proc or lambda work well till there is no uploaded content present.
..., if => Proc.new{|company| company.logo.present?}
@company.save #works will when @company contains correct mime type logo file
@company.save #fails when @company contains no logo file
As soon as someone uploads the logo it save the object correctly and starts raising wrong mime types exception on any other save where no image upload present.
回答1:
Try to add if condition. For example:
validates :logo, :file_mime_type => {:content_type => /image/}, :if => Proc.new{|img| img.logo.present?}
回答2:
I ran into this when I was trying to save the model that contained the carrierwave attribute, say the title of the image in your example.
validates :logo, :file_mime_type => { :content_type => /image/ },
:if => Proc.new{ |img| img.logo.present? and img.logo_changed? }
_changed? is available to tell if that specific attribute was changed: How to detect attribute changes from model?
回答3:
as stated in the doc for carrierwave.
class MyUploader < CarrierWave::Uploader::Base
def extension_white_list
%w(jpg jpeg gif png)
end
end
来源:https://stackoverflow.com/questions/14768717/rails-custom-validator-to-validate-mime-types-with-carrier-wave