Skip to content

Instantly share code, notes, and snippets.

@lorenadl
Last active January 25, 2024 00:11
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lorenadl/a1eb26efdf545b4b2b9448086de3961d to your computer and use it in GitHub Desktop.
Save lorenadl/a1eb26efdf545b4b2b9448086de3961d 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

@gr8bit
Copy link

gr8bit commented Jun 10, 2020

Yes, but sticking to your example, the security team checks all the deposited suitcases before storing them (in the planes). The airport needs to handle both checking and storage.

In reality, Rails is a secure web framework, so I was confused it simply seemed not to offer the xray. It does though, sometimes we seem to cause "empty" uploads which cannot be analyzed (because they're empty), so that's a fault on my site. Rails' xray is in place and works. :)

@hassam-saeed
Copy link

undefined method `content_type' for #ActiveStorage::Attached::Many:0x00007fdb4cbce6f0
How to resolve this?

@chase439
Copy link

@b-nik, Rails 6 has fixed the issue (Store newly-uploaded files on save rather than assignment). rails/rails@e8682c5

@brendon
Copy link

brendon commented Oct 20, 2021

Of the two available gems I went with https://github.com/aki77/activestorage-validator as it is much simpler. You probably don't even need the gem as you could just bring in the validator class.

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