ActiveStorage File Attachment Validation

前端 未结 7 539
暖寄归人
暖寄归人 2021-01-31 10:01

Is there a way to validate attachments with ActiveStorage? For example, if I want to validate the content type or the file size?

Something like Paperclip\'s approach wou

7条回答
  •  离开以前
    2021-01-31 10:16

    Well, it ain't pretty, but this may be necessary until they bake in some validation:

      validate :logo_validation
    
      def logo_validation
        if logo.attached?
          if logo.blob.byte_size > 1000000
            logo.purge
            errors[:base] << 'Too big'
          elsif !logo.blob.content_type.starts_with?('image/')
            logo.purge
            errors[:base] << 'Wrong format'
          end
        end
      end
    

提交回复
热议问题