【问题标题】:How to improve and run a custom validation method?如何改进和运行自定义验证方法?
【发布时间】:2011-08-15 16:41:02
【问题描述】:

我正在使用 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 有效)。

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

【问题讨论】:

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


    【解决方案1】:

    它已经包含在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 中验证 - 这是模型工作。只是

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

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

    【讨论】:

      【解决方案2】:

      您确实应该将验证移至模型。这是一个例子:

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

      【讨论】:

        猜你喜欢
        • 2015-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-10
        • 2018-05-12
        • 1970-01-01
        相关资源
        最近更新 更多