rails定制验证器,用于使用载波验证mime类型 [英] rails custom validator to validate mime types with carrier wave

查看:149
本文介绍了rails定制验证器,用于使用载波验证mime类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下方式通过载波验证上传文件内容的mime类型.

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?

谢谢!!

更新:

使用proc或lambda效果很好,直到没有上传的内容为止.

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  

只要有人上载徽标,它就会正确保存对象,并在没有图像上传的任何其他保存上开始引发错误的mime类型异常.

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.

推荐答案

当我尝试保存包含载波属性的模型时遇到了这个问题,例如在示例中说图像的标题.

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?可用于判断特定属性是否已更改:如何从模型中检测属性更改?

_changed? is available to tell if that specific attribute was changed: How to detect attribute changes from model?

这篇关于rails定制验证器,用于使用载波验证mime类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆