6

I am using rails 5.2, bootstrap-4, bootstrap_form with active-storage file is uploading successfully. What I want is when I enter company name in form then it should check for company_logo.

I tried with this it is working good when I include error loop in form Here in view

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

Model Code

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 I want this kind of validation with file field

Tanay Sharma
  • 1,098
  • 10
  • 29

2 Answers2

3

Actually active_storage doesn't support validation.

What i did for presence :

  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

But this will upload the file to your storage and create an active_storage blob field in database...

The only workarround i found to delete file on storage and database field (so ugly):

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
D1ceWard
  • 972
  • 8
  • 17
  • 1
    when there is validation for another field and file is in `file_field`, like you said file is uploaded and create an `active_storage` blob field in database so is there any way to insert into another table `active_record_attachments` so file is uploaded it doesn't depend on other form error because if there is validation in form user have to upload file another time that is not correct – Tanay Sharma Apr 17 '18 at 07:16
1

A nice solution is the active_storage_validations gem. Add to your Gemfile, then bundle install:

# Gemfile
gem 'active_storage_validations'

Inside your model, try something like this for a video attachment:

has_one_attached :video

validates :video,
size: { less_than: 50.megabytes, 
  message: 'Video size cannot be larger than 50 megabytes.' },
content_type: 
{ in: %w(video/mov video/quicktime video/mp4 video/avi video/mpeg), 
  message: 'Upload must be a valid video type' }

References

  • The readme has many very useful examples.
  • This question and answers has some relevant information too.
stevec
  • 41,291
  • 27
  • 223
  • 311