Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Active storage validation errors with form errors

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

like image 509
t s Avatar asked Oct 17 '22 20:10

t s


2 Answers

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
like image 182
D1ceWard Avatar answered Oct 21 '22 00:10

D1ceWard


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.
like image 39
stevec Avatar answered Oct 21 '22 00:10

stevec