Skip to content

How to: Validate uploads with Active Record

Weston Ganger edited this page Feb 10, 2017 · 5 revisions

Standard Active Model validations can be used to ensure a file is uploaded:

mount_uploader :avatar, AvatarUploader
validates_presence_of :avatar

or, when using the mount_on option

mount_uploader :avatar, AvatarUploader, :mount_on => :file_name
validates_presence_of :avatar

So, as you can see, we validate the presence of the uploaded file (not the underlying column on which it's mounted). This works because the mounted uploader implements the "present?" method used by the validation API.

CarrierWave also supplies additional validations, such as validating the integrity of an uploaded file and validating that the file was successfully processed:

validates_integrity_of :avatar
validates_processing_of :avatar

These two validations are both on by default according to the CarrierWave config.

The validations use translated error messages and can be changed using i18n localization:

en:
  errors:
    messages:
      carrierwave_processing_error: failed to be processed
      carrierwave_integrity_error: is not an allowed file type
Clone this wiki locally