rails custom validator to validate mime types with

2019-09-03 05:01发布

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.

3条回答
Juvenile、少年°
2楼-- · 2019-09-03 05:28

Try to add if condition. For example:

validates :logo, :file_mime_type => {:content_type => /image/}, :if => Proc.new{|img| img.logo.present?}

查看更多
Root(大扎)
3楼-- · 2019-09-03 05:33

as stated in the doc for carrierwave.

class MyUploader < CarrierWave::Uploader::Base
  def extension_white_list
   %w(jpg jpeg gif png)
  end
end
查看更多
Root(大扎)
4楼-- · 2019-09-03 05:38

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?

查看更多
登录 后发表回答