If you are open for adding a new gem then I would highly recommend using popular Paperclip
gem which has built-in validations for file size
, content type/ extension
and presence
.
Refer to Paperclip Github Documentation.
It would be as simple as saying
validates_attachment :image, :presence => true,
:content_type => { :content_type => ["image/jpg", "image/jpeg", "image/gif", "image/png"] },
:size => { :in => 0..10.kilobytes }
For a model with field named image
(Paperclip attachment).
Where:
:presence
Validates that a file was attached while form submission
:content_type
Validates file extensions(mime-type) specified. It will also check the actual content of the uploaded file. Read my findings here.
:size
Validates the uploaded file size against the given range.