Warning: Creating default object from empty value in /homepages/39/d161420129/htdocs/p373.net/wp/wp-content/themes/p373b/admin/functions.php on line 183
Carrierwave custom validations

Carrierwave custom validations

The use case here is when you need to conditionally validate the extensions you validate.  In our case, we only wanted to validate the extension white list when a local file was uploaded.  This is because our users can signup via Yammer during which we suck in their mugshot images.  Yammer’s mugshot urls do not have extensions so we need to bypass the whitelist validation during this process.

This is easy enough using Carrierwave’s validates_integrity_of method.

class AvatarAttachment < ActiveRecord::Base
  mount_uploader :file, AvatarAttachmentUploader
  belongs_to :user
  validates_integrity_of :file, if: :should_validate_file
  def should_validate_file
    return (self.changes[:file] and self.file.present?) 

We just check if there is a file present; in the case of remote file urls, file is nil and remote_file_url is populated.

Simple and powerful.  Just the way I like it.

    This entry was posted in Coding, Ruby/Rails, Technology and tagged , . Bookmark the permalink. Both comments and trackbacks are currently closed.