Tintin81 Tintin81 - 4 years ago 145
Ruby Question

How to change CarrierWave's min_size & max_size error messages?

I am using the following method to validate the file size of my images:

class ImageUploader < CarrierWave::Uploader::Base

def size_range
0..200.kilobytes
end


Unfortunately, the error message that my users are getting is a bit cryptic:


Image size should be less than 204800


Is there a way to change that to something more meaningful such as:


Image size should be less than 2 MB


I've tried various approaches but to no avail.

These are my localization files by the way:

errors:
messages:
min_size_error: size should be greater than %{min_size}
max_size_error: size should be less than %{max_size}


Thanks for any help.

Answer Source

To make an error message more friendly override carrierwave's check_size! method in your FileUploader with below code:

class ImageUploader < CarrierWave::Uploader::Base

  def size_range
    0..200.kilobytes
  end

  private

  def check_size!(new_file)
    size = new_file.size
    expected_size_range = size_range
    if expected_size_range.is_a?(::Range)
      if size < expected_size_range.min
        raise CarrierWave::IntegrityError, I18n.translate(:"errors.messages.min_size_error", :min_size => ApplicationController.helpers.number_to_human_size(expected_size_range.min))
      elsif size > expected_size_range.max
        raise CarrierWave::IntegrityError, I18n.translate(:"errors.messages.max_size_error", :max_size => ApplicationController.helpers.number_to_human_size(expected_size_range.max))
      end
    end
  end
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download