Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tteurs/625b26c839d07232e903eac309f4f873 to your computer and use it in GitHub Desktop.
Save tteurs/625b26c839d07232e903eac309f4f873 to your computer and use it in GitHub Desktop.
[Rails] Active Storage how to validate file type

Rails Active Storage how to restrict uploadable file types

Active Storage doesn't have validations yet.

We can restrict the accepted file types in the form:

<div class="field">
  <%= f.label :deliverable %>
  <%= f.file_field :deliverable, direct_upload: true, 
    accept: 'application/pdf, 
    application/zip,application/vnd.openxmlformats-officedocument.wordprocessingml.document' %>
 </div>

And add a custom validation in the model:

class Item
  has_one_attached :document

  validate :correct_document_mime_type

  private

  def correct_document_mime_type
    if document.attached? && !document.content_type.in?(%w(application/msword application/pdf))
      errors.add(:document, 'Must be a PDF or a DOC file')
    end
  end
end

Source: https://stackoverflow.com/questions/48349072/ruby-on-rails-active-storage-how-to-accept-only-pdf-and-doc?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment