How to display a presence validation conditionally in combination with carrierwave?

非 Y 不嫁゛ 提交于 2019-12-10 18:22:00

问题


I've an image model with the following validation

validates :image, presence: true, image_size: { width: { min: 400 },
height: { min: 400 } }, :file_size => { :maximum => 5.megabytes.to_i }

now I also have a carrierwave validation:

def extension_whitelist
  %w(jpg jpeg gif png)
end

When I submit a .txt file I get the following:

The form contains 2 errors. Image can't be blank Image You are not allowed to upload "txt" files, allowed types: jpg, jpeg, gif, png

The first error message shouldn't be there. Because I'm actually submitting something.

How to remove this first error message? Image can't be blank


回答1:


You could skip the presence validation if there is no image integrity error:

class User < ApplicationRecord
  mount_uploader :image, ImageUploader

  validates :image,
            presence: true,
            if: ->(record) { record.image_integrity_error.blank? }
end

user = User.new(image: File.open('tmp/.keep'))
user.valid? #=> false
user.errors.full_messages
#=> ["Image You are not allowed to upload \"\" files, allowed types: jpg, jpeg, gif, png"]


来源:https://stackoverflow.com/questions/48098304/how-to-display-a-presence-validation-conditionally-in-combination-with-carrierwa

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