Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Active Storage - how to accept only pdf and doc?

Is it possible to add a validation to accept only .pdf and .doc files using Active Storage?

like image 463
Magda Sz. Avatar asked Jan 19 '18 20:01

Magda Sz.


People also ask

How does active storage work in Rails?

Active Storage uses two tables in your application's database named active_storage_blobs and active_storage_attachments . After creating a new application (or upgrading your application to Rails 5.2), run rails active_storage:install to generate a migration that creates these tables.

How do I get an image URL from active storage?

image. service_url . This will give you the url where the image is saved. I.E.

What is Activestorage?

1 What is Active Storage? Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.


2 Answers

Adding a gem for just a few lines of code is not always needed. Here's a working example based on a small alteration on the example above.

validate :logo_content_type, if: -> { logo.attached? }


def logo_content_type
  allowed = %w[image/jpeg image/jpeg image/webp image/png]
  if allowed.exclude?(logo.content_type)
    errors.add(:logo, message: 'Logo must be a JPG, JPEG, WEBP or PNG')
  end
end
like image 161
Thomas Van Holder Avatar answered Oct 12 '22 23:10

Thomas Van Holder


there is a gem which provides validation for active storage

gem 'activestorage-validator'

https://github.com/aki77/activestorage-validator

  validates :avatar, presence: true, blob: { content_type: :image }
  validates :photos, presence: true, blob: { content_type: ['image/png', 'image/jpg', 'image/jpeg'], size_range: 1..5.megabytes }
like image 42
Confused Vorlon Avatar answered Oct 13 '22 00:10

Confused Vorlon