如何验证扩展 "pdf"
How to validate the extension "pdf"
我需要验证来检查文件扩展名,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 用于活动存储验证:active_storage_validations
我用这个gem,我推荐给你。你可以这样使用它:
validates :user_file, content_type: ['application/pdf']
我需要验证来检查文件扩展名,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 用于活动存储验证:active_storage_validations
我用这个gem,我推荐给你。你可以这样使用它:
validates :user_file, content_type: ['application/pdf']