开发者

How to improve and run a custom validation method?

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开发者_JS百科 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 Paperclip and it do just the same job. so why do you want to repet it?

class Avatar < ActiveRecord::Base
  has_attached_file :file
  validates_attachment_presence :file
  validates_attachment_size :file, :less_than => 5.megabytes
  validates_attachment_content_type :file, :content_type => ['image/jpeg', 'image/png']
end

and never validate in Controller - it is Model job. Just

@user = User.new(params[:user])
@user.save

It won't save @user if @user.avatar won't pass validation


You should really move validations to a model. Here is an example:

validate :avatar_should_be_valid

def :avatar_should_be_valid
errors.add(:base, "avatar is invalid!") if...
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜