显示带有表单错误的活动存储验证错误

时间:2018-04-16 13:57:44

标签: ruby-on-rails rails-activestorage ruby-on-rails-5.2

我正在使用rails 5.2bootstrap-4bootstrap_formactive-storage文件正在成功上传。我想要的是当我在表单中输入公司名称时,它应该检查company_logo

我试过这个,当我在表单中包含错误循环时,它运行良好 在视图中

- if @company.errors.any?
  #error_explanation
    %ul
      - @company.errors.full_messages.each do |message|
        %li= message

型号代码

has_one_attached :company_logo
validates :name, :company_logo,presence: true
after_validation :is_logo?, if: Proc.new { |a| a.name? }


def is_logo?
      errors.add(:base, 'Please upload your company logo.') if !self.company_logo.attached?
end

我想用文件字段进行这种验证 I want this kind of validation with file field

1 个答案:

答案 0 :(得分:3)

实际上,active_storage不支持验证。

我为在场做了什么:

  class CompanyModel < ApplicationRecord
    has_one_attached :company_logo

    validate :company_logo?

    private

    def company_logo?
      errors.add(:base, 'Please upload your company logo.') unless company_logo.attached?
    end
  end

但是这会将文件上传到您的存储空间并在数据库中创建一个active_storage blob字段...

我发现只删除存储和数据库字段上的文件(如此难看):

def company_logo?
  # Clean exit if there is a logo
  return if company_logo.attached?

  # Unless add error
  errors.add(:base, 'Please upload your company logo.')

  # Purge the blob
  company_logo.record.company_logo_attachment.blob.purge

  # Purge attachment
  company_logo.purge
end