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
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
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' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With