【发布时间】:2019-09-11 12:50:48
【问题描述】:
如果在 ActiveStorage 中上传的文件是 pdf,我需要验证以检查文件扩展名。
我厌倦了下面的验证,但是显示错误消息,与哪个文件扩展名(也是 pdf 文件)无关...
validate :user_file_type, if: :is_existing?
def user_file_type
extension = ['file/pdf']
errors.add(:user_file, "must be a PDF") unless
user_file.blob.content_type.in?(extension)
end
def is_existing?
self.user_file.attached?
end
有人知道我应该如何编写验证,以便仅在上传非 pdf 时显示错误消息?谢谢
【问题讨论】:
-
有一个用于主动存储验证的 gem:github.com/igorkasyanchuk/active_storage_validations
-
哇!它正在工作。非常感谢!!
-
我将其添加为答案
标签: ruby-on-rails validation pdf rails-activestorage