Created
February 10, 2017 21:07
-
-
Save weedySeaDragon/566d2b95602626905f7d3efc96cc783c to your computer and use it in GitHub Desktop.
Paperclip file size validation error messsages - a little readme comment and example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is a file used in the SHF-project that uses the paperclip gem. | |
# I wrote a big comment that explains using error messages for (paperclip) size validation. | |
class UploadedFile < ApplicationRecord | |
belongs_to :membership_application | |
has_attached_file :actual_file | |
validates_attachment :actual_file, content_type: {content_type: ['image/jpeg', | |
'image/gif', | |
'image/png', | |
'text/plain', | |
'text/rtf', | |
'application/pdf', | |
'application/msword', | |
'application/vnd.openxmlformats-officedocument.wordprocessingml.document', | |
'application/vnd.ms-word.document.macroEnabled.12'], | |
message: I18n.t('membership_applications.uploads.invalid_upload_type')}, | |
size: { in: 0..5.megabytes, | |
message: :file_too_large | |
} | |
=begin | |
If the size validation fails, then the error message is looked up in the | |
locale file(s) starting based on I18n conventions, then adding 'actual_file_file' | |
as the attribute, and finally adding 'file_too_large' which is what is specified by the | |
'message' key within the 'size' hash above. For some reason, the Paperclip gem will | |
raise (or find) 2 error messages: the one for 'actual_file_file_size' and | |
one for 'actual_file'. | |
Here's an example of the error messages in the en.yml locale file: | |
en: | |
activerecord: | |
models: | |
uploaded_file: | |
attributes: | |
actual_file_file_size: | |
file_too_large: 'The uploaded file is too big.' | |
actual_file: | |
file_too_large: 'The uploaded file size must be smaller than %{max}. (Your file is %{value} bytes.)' | |
Paperclip makes some instance variables available to you so that you can use them | |
in the error messages if you want. These variables are made available by the | |
size validator: Paperclip::Validators::AttachmentSizeValidator. Specifically, | |
the 'validate_each' method adds the instance variables :min, :max, and :count | |
available and passes them to the error messages. You can choose to | |
use them in the messages (in the locale .yml files) or not. | |
min = the lower bound of the file size | |
max = the upper bound of the file size | |
count = the upper bound, converted to 'human_size' by ActiveSupport::NumberHelper.number_to_human_size(size) | |
value = the actual size of the file | |
=end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment