Home > Blockchain >  How to restrict file type in Rails has_many_attached
How to restrict file type in Rails has_many_attached

Time:12-02

In my Rails application, User has_many_attached :resumes. My user class looks like below

class User < ApplicationRecord
  has_many_attached :resumes, dependent: :destroy
end

Every thing is working fine, users are able to upload their resumes. But the problem is that user can upload file with any extension. For example user can upload image file rather than document or pdf file for resume. What I want to achieve is allow users to upload file with these extensions only .doc, .docx, .pdf, .txt and .rtf. I also want to make sure that file size is not greater than 2mb. How can I achieve this in Rails ? I am not sure how to write custom validation for these 2 requirements.

Thanks in Advance.

CodePudding user response:

You need to use the Active Storage Validation gem for that. You can also check the documentation here.

The TLDR is that you need to have two separate validations one for the type and one for the size.

validates :resumes, attached: true, content_type: ['application/pdf', ..., '']
validates :resumes, attached: true, size: { less_than: 2.megabytes }

You could also use a UI that blocks unsupported file types. Have a look at the find_field method here.

  • Related