Ruby on rails 验证图片是否存在时出错Rails 4
这是我的演出模型Ruby on rails 验证图片是否存在时出错Rails 4,ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller,model,Ruby On Rails,Ruby,Ruby On Rails 4,Model View Controller,Model,这是我的演出模型 class Gig < ActiveRecord::Base has_attached_file :image, :styles => { :medium => "360x170>", :bigger => "650x459>" } validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ validate :image_size_v
class Gig < ActiveRecord::Base
has_attached_file :image, :styles => { :medium => "360x170>", :bigger => "650x459>" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
validate :image_size_validation
def image_size_validation
if image.size > 2.megabytes
errors.add(:base, "Image should be less than 2MB")
end
end
end
该错误显然是由以下行引发的:
if image.size > 2.megabytes
显然,如果没有图像。。。它没有尺码
你在那里查一查零怎么样:
def image_size_validation
return if image.blank?
if image.size > 2.megabytes
使用您的方法,表单将在没有图像的情况下保存,此时表单应向用户显示“添加图片之前无法继续”的通知。缺少的图像应通过状态验证捕获。(如果需要,添加类似:
validates:image,presence:true
的内容)这只是确保没有图像时图像大小验证不会爆炸
def image_size_validation
return if image.blank?
if image.size > 2.megabytes