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

Magda Sz. picture Magda Sz. · Jan 19, 2018 · Viewed 10.5k times · Source

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

Answer

michalvalasek picture michalvalasek · Jan 23, 2018

Currently you have to write your own validator which looks at the attachment's MIME type:

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))
      document.purge # delete the uploaded file
      errors.add(:document, 'Must be a PDF or a DOC file')
    end
  end
end

Also, there are some useful shortcut methods image?, audio?, video? and text? that check against multiple mime types.