Carrierwave-如果文件类型不在白名单中,则会触发状态验证 [英] Carrierwave - Presence validation triggering if filetype not on whitelist
问题描述
在我的Rails 4应用程序中,我正在使用载波上传图像.
In my rails 4 app I am using carrierwave to upload images.
class UserItemImage < ActiveRecord::Base
include PicturesHelper
attr_accessor :foo
mount_uploader :picture, PictureUploader
belongs_to :user_item
validate :picture_size
validates :picture, presence: true
end
我正在 picture_uploader.rb
def extension_white_list
%w(jpg jpeg png)
end
我的表格
<%= simple_form_for :user_item_image, url: user_item_user_item_images_path(@user_item), multipart: true do |f| %>
<%= f.input :picture, as: :file, label: false, input_html: {multiple: true, class: 'image-file'} %>
当我尝试附加扩展名不在白名单中的文件时.我收到不能为空"的错误消息.如果我删除在线状态验证,则white_list验证错误将正确显示.我确实希望显示文件扩展名错误消息,因为从技术上讲它不是空白的,只是文件不正确.
When I try attaching a file with an extension not on the whitelist. I am getting a "can't be blank" error message. If I remove the presence validation, then the white_list validation error displays correctly. I really want the file extension error message to show up instead, because technically it's not blank it just has an incorrect file.
推荐答案
我遇到了同样的问题,最终还是这样做了:
I have the same problem and ended up doing this:
1)确保在验证之前放置 mount_uploader:attachment,AttachmentUploader
.
1) Make sure to put mount_uploader :attachment, AttachmentUploader
before validations.
2)
validates :attachment, presence: true, unless: :attachment_errors_exist?
def attachment_errors_exist?
errors[:attachment].present?
end
我发现是否存在其他错误(很可能是 extension_white_list_error
),那么附件必须已经存在,对吗?我想您可以进一步检查消息本身以确定它是否为 extension_white_list_error
,但这对我来说已经足够了.
I figured if other errors exist (most likely it's extension_white_list_error
), then the attachment must be present already, right? I guess you can further examine the message itself to determine whether it is extension_white_list_error
, but this is good enough for me.
这篇关于Carrierwave-如果文件类型不在白名单中,则会触发状态验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!