Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Message < ActiveRecord::Base
validate :image_size_validation, :if => Proc.new { |m| m.image.present? }
mount_uploader :image, MessageImageUploader
private
def image_size_validation
errors[:image] << "should be less than 2MB" if image.size > 2.megabytes
end
end
@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Apr 18, 2011

Replace this:

validate :image_size_validation, :if => Proc.new { |m| m.image.present? }

with that:

validate :image_size_validation, :if => "image?"

for cleaner code.

@jpemberthy

This comment has been minimized.

Copy link
Owner Author

@jpemberthy jpemberthy commented Apr 21, 2011

Ah that's sugar, thanks!

@chrisbloom7

This comment has been minimized.

Copy link

@chrisbloom7 chrisbloom7 commented Jun 6, 2011

I took your basic idea and turned it into a Rails 3 style validator. It's basically a clone of the built-in validates_length_of validator, but checks the file size instead. https://gist.github.com/1009861

@jpemberthy

This comment has been minimized.

Copy link
Owner Author

@jpemberthy jpemberthy commented Jun 6, 2011

Cool, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment