问题
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