使活动存储 has_one_attatched 不为空
Make Active Storage has_one_attatched not null
我有一个带有活动存储的模型,设置了 has_one_attached,一些用户在没有向表单添加文件的情况下点击了提交。在我向前端添加验证之前,我想确保后端将拒绝没有附件的记录。
我如何设置一个模型,除非活动存储 has_one_attached 中有东西,否则它不会保存?
我认为,目前唯一的选择是遵循 'regular' 路径:
将 include ActiveModel::Validations
和 validates_with QwertieCustomValidator
添加到您的模型,在 app/validators
下创建自定义验证器并在那里检查是否 record.attached_file.attached?
,如果否,添加错误:record.errors.add(:attached_file, 'no file was attached')
转念一想,你不需要在其他文件中指定验证器,我只是在我的项目中这样做以匹配改编项目的流程。最短路线如下所示:
has_one_attached :attached_file
validate :check_file_presence
def check_file_presence
errors.add(:attached_file, "no file added") unless attached_file.attached?
end
希望对你有所帮助。
我有一个带有活动存储的模型,设置了 has_one_attached,一些用户在没有向表单添加文件的情况下点击了提交。在我向前端添加验证之前,我想确保后端将拒绝没有附件的记录。
我如何设置一个模型,除非活动存储 has_one_attached 中有东西,否则它不会保存?
我认为,目前唯一的选择是遵循 'regular' 路径:
将 include ActiveModel::Validations
和 validates_with QwertieCustomValidator
添加到您的模型,在 app/validators
下创建自定义验证器并在那里检查是否 record.attached_file.attached?
,如果否,添加错误:record.errors.add(:attached_file, 'no file was attached')
转念一想,你不需要在其他文件中指定验证器,我只是在我的项目中这样做以匹配改编项目的流程。最短路线如下所示:
has_one_attached :attached_file
validate :check_file_presence
def check_file_presence
errors.add(:attached_file, "no file added") unless attached_file.attached?
end
希望对你有所帮助。