Skip to content

How to: Validate attachment file size

Rahul Jayaraman edited this page May 25, 2013 · 3 revisions

You can use a Rails custom validator to verify your attachment meets specific file size requirements.

Grab a copy of the validator from https://gist.github.com/1009861 and save it to your lib/ folder as file_size_validator.rb. Add the error translations to config/locales/en.yml or wherever is appropriate for your setup. Then do this in your parent model:

# app/models/brand.rb 
require 'file_size_validator' 
class Brand < ActiveRecord::Base 
  mount_uploader :logo, BrandLogoUploader 
  validates :logo, 
    :presence => true, 
    :file_size => { 
      :maximum => 0.5.megabytes.to_i 
    } 
end 

Like validates_length_of, validates_file_size accepts :maximum, :minimum, :in [range], and :is options.


A custom validator could also be used like this.

# app/models/user.rb 
class User< ActiveRecord::Base 
  attr_accessible :product_upload_limit
  has_many :products
end

# app/models/brand.rb 
class Product < ActiveRecord::Base 
  mount_uploader :file, FileUploader
  belongs_to :user
  validate :file_size

  def file_size
    if file.file.size.to_f/(1000*1000) > user.product_upload_limit.to_f
      errors.add(:file, "You cannot upload a file greater than #{upload_limit.to_f}MB")
    end
  end
 end

Here, the upload limit varies from user to user & is saved in the user model.

Clone this wiki locally