验证失败时如何防止主动存储更新模型?
How to prevent active storage updating model when validation fails?
我的用户模型has_one_attached :avatar
这里我有一些验证方法
validate :validate_avatar_presence
validate :validate_avatar_format
validate :validate_avatar_size
private
def validate_avatar_presence
errors.add(:avatar, 'should exist') unless self.avatar.attached?
end
def validate_avatar_size
if self.avatar.attached?
purge_avatar('File is too big') if self.avatar.blob.byte_size > 2000000
end
end
def validate_avatar_format
if self.avatar.attached?
purge_avatar('Wrong format') unless self.avatar.blob.content_type.starts_with?('image/')
end
end
def purge_avatar(msg)
errors.add(:avatar, msg)
avatar.purge_later
end
无论我上传什么,用户头像都会更新。如果验证失败,头像变为零,否则我得到我上传的内容。我试图通过 before_update 回调进行验证。没用。
似乎 ActiveStorage 目前不支持验证。根据https://github.com/rails/rails/issues/31656.
Active Storage 目前不支持验证,但 Rails 6.0 中将提供全面支持。在 6.0 发布之前,使用 Rails master,即 avoids storing files when validations fail.
我的用户模型has_one_attached :avatar
这里我有一些验证方法
validate :validate_avatar_presence
validate :validate_avatar_format
validate :validate_avatar_size
private
def validate_avatar_presence
errors.add(:avatar, 'should exist') unless self.avatar.attached?
end
def validate_avatar_size
if self.avatar.attached?
purge_avatar('File is too big') if self.avatar.blob.byte_size > 2000000
end
end
def validate_avatar_format
if self.avatar.attached?
purge_avatar('Wrong format') unless self.avatar.blob.content_type.starts_with?('image/')
end
end
def purge_avatar(msg)
errors.add(:avatar, msg)
avatar.purge_later
end
无论我上传什么,用户头像都会更新。如果验证失败,头像变为零,否则我得到我上传的内容。我试图通过 before_update 回调进行验证。没用。
似乎 ActiveStorage 目前不支持验证。根据https://github.com/rails/rails/issues/31656.
Active Storage 目前不支持验证,但 Rails 6.0 中将提供全面支持。在 6.0 发布之前,使用 Rails master,即 avoids storing files when validations fail.