rails custom validator to validate mime types with carrier wave

时光怂恿深爱的人放手 提交于 2019-12-12 02:19:37

问题


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

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