I am using Ruby on Rails 3.0.9 and Paperclip 2.3. Since the Paperclip gem offers only two validation methods (validates_attachment_presence and validates_attachment_content_type) I am trying to implement my custom validation methods.
In my model file I have just the following validation method
def validates_avatar(attribute_name, file)
if file.nil? # file value is nil if no file is uploaded
self.errors.add( "#{attribute_name}", "You must select a file" )
else
self.errors.add( "#{attribute_name}", "Avatar is an invalid image format") unless MIME_TYPES.include?(file.content_type)
self.errors.add( "#{attribute_name}", "Avatar is too big" if ( ( file.size > AVATAR_FILE_MAX_SIZE.to_i ) || ( file.size == nil ) )
end
return self.errors.empty?
end
that I call from my controllers in this way:
if @user.validates_avatar(:avatar, params[:user][:avatar])
...
end
I would like to make the above validation to run\to trigger the same way of all others Ruby on Rails validation methods (eg: as-like validates :title, :presence => true works).
How can I do that and how can I improve the above code in order to handle avatar validations?
It is already included in
Paperclipand it do just the same job. so why do you want to repet it?and never validate in Controller – it is Model job. Just
It won’t save
@userif@user.avatarwon’t pass validation