Search code examples
ruby-on-railsvalidationpdfrails-activestorage

How to validate the extension "pdf"


I need a validation to check the file extension, if uploaded file in ActiveStorage is pdf or not.

I tired with below validation, however an error message shows, doesn't matter which file extension (also pdf file)...

validate :user_file_type, if: :is_existing?
  def user_file_type
    extension = ['file/pdf']
    errors.add(:user_file, "must be a PDF") unless 
    user_file.blob.content_type.in?(extension)
  end

  def is_existing?
    self.user_file.attached?
  end

Does someone know how should I write the validation, so that an error message shows only if non-pdf was uploaded? Thanks


Solution

  • There is a gem for active storage validations: active_storage_validations

    I use this gem and I recommend it to you. You can use it like this:

    validates :user_file, content_type: ['application/pdf']