如何改进和运行自定义验证方法?

时间:2011-08-15 16:41:02

标签: ruby-on-rails ruby ruby-on-rails-3 validation paperclip

我正在使用Ruby on Rails 3.0.9和Paperclip 2.3。由于Paperclip gem仅提供两种验证方法(validates_attachment_presencevalidates_attachment_content_type),因此我尝试实现自定义验证方法。

在我的模型文件中,我只是以下验证方法

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

我以这种方式从我的控制器打来电话:

if @user.validates_avatar(:avatar, params[:user][:avatar])
  ...
end

我想让上面的验证运行\以触发所有其他Ruby on Rails验证方法的相同方式(例如:as-like validates :title, :presence => true有效)。

我该怎么做?我如何改进上述代码以处理头像验证?

2 个答案:

答案 0 :(得分:3)

它已经包含在Paperclip中,它完成了同样的工作。那你为什么要重复呢?

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

并且永远不会在Controller中验证 - 它是Model工作。只是

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

如果@user无法通过验证,则不会保存@user.avatar

答案 1 :(得分:1)

您应该将验证移到模型中。这是一个例子:

validate :avatar_should_be_valid

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