【问题标题】:Make Active Storage has_one_attatched not null使 Active Storage has_one_attatched 不为空
【发布时间】:2018-11-05 01:09:18
【问题描述】:

我有一个使用 has_one_attached 设置的具有活动存储的模型,并且一些用户在没有向表单添加文件的情​​况下点击了提交。在向前端添加验证之前,我想确保如果记录没有附加文件,后端将拒绝该记录。

如何设置模型,使其不会保存,除非活动存储 has_one_attached 中有东西?

【问题讨论】:

    标签: ruby-on-rails rails-activestorage


    【解决方案1】:

    我认为,目前唯一的选择是遵循“常规”路径: 将include ActiveModel::Validationsvalidates_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
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2022-11-28
      • 2019-12-24
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2019-02-16
      • 2020-05-16
      相关资源
      最近更新 更多