Active Storage Validations 使用教程
项目介绍
active_storage_validations
是一个用于 Rails 应用的 gem,它为 Active Storage 提供了简单的验证功能。如果你在使用 Active Storage 并希望添加简单的验证,如文件存在性、内容类型、文件大小、图像/视频尺寸、上传文件数量、长宽比等,这个 gem 可以为你提供便利。
项目快速启动
安装
首先,在你的 Gemfile 中添加以下内容:
gem 'active_storage_validations'
然后运行:
bundle install
使用示例
在你的模型中,你可以添加各种验证:
class User < ApplicationRecord
has_one_attached :avatar
has_many_attached :photos
validates :avatar, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 500.kilobytes }
validates :photos, limit: { min: 1, max: 3 }, dimension: { width: { in: 800..1600 } }
end
应用案例和最佳实践
验证文件存在性
validates :avatar, attached: true
验证内容类型
validates :avatar, content_type: ['image/png', 'image/jpg', 'image/jpeg']
验证文件大小
validates :avatar, size: { less_than: 500.kilobytes }
验证图像尺寸
validates :avatar, dimension: { width: { in: 800..1600 } }
验证上传文件数量
validates :photos, limit: { min: 1, max: 3 }
典型生态项目
active_storage_validations
通常与其他 Rails 生态系统中的 gem 一起使用,例如:
active_storage
:用于文件上传和管理。mini_magick
:用于图像处理。ruby-vips
:用于更高效的图像处理。
这些工具和 gem 共同构成了一个强大的 Rails 文件处理和验证生态系统,使得开发复杂的文件上传和处理功能变得更加简单和高效。