2015-10-06 58 views
0

我想在我的组织模型中进行验证,只有在选择上传图片文件时才会运行。有条件验证:如果文件上传,然后检查最小大小

应用程序/模型/ organisation.rb

class Organisation < ActiveRecord::Base 

    validates :name, :url, :street, :city, :zipcode, presence: true 

    validate :validate_minimum_image_size, if: # file is selected for upload 


    def validate_minimum_image_size 
    image = MiniMagick::Image.open(picture.path) 
    unless image[:width] > 300 && image[:height] > 300 
     errors.add :image, "should be 300px minimum!" 
    end 
    end 

end 

有没有办法当选择图像文件上传检查图像的大小?

回答

1

您可以提供自己的自定义方法某物像:

validate :validate_minimum_image_size, if: :file_present? 

    def file_present? 
    picture ? true : false 
    end 
+0

感谢dsounded! – StandardNerd