Ruby on Rails。自定义验证器方法中的自定义消息

时间:2010-09-12 09:42:53

标签: ruby-on-rails ruby validation

我希望能够在模型验证器方法中设置自定义消息,以通知用户输入数据不正确。

首先,我设置了一个自定义验证器类,我以recommended in rails' documentation的方式重新定义了validate_each方法:


# app/models/user.rb

# a custom validator class
class IsNotReservedValidator < ActiveModel::EachValidator
  RESERVED = [
    'admin',
    'superuser'
  ]

  def validate_each(record, attribute, value)
    if RESERVED.include? value
      record.errors[attribute] <<
        # options[:message] assigns a custom notification
        options[:message] || 'unfortunately, the name is reserved'
    end
  end
end

辅助,我尝试通过两种不同的方式将自定义消息传递给validates方法:


# a user model
class User < ActiveRecord::Base
  include ActiveModel::Validations

  ERRORS = []

  begin
    validates :name,
      :is_not_reserved => true,
      # 1st try to set a custom message
      :options         => { :message => 'sorry, but the name is not valid' }
  rescue => e
    ERRORS << e
    begin
      validates :name,
        :is_not_reserved => true,
        # 2nd try to set a custom message
        :message         => 'sorry, but the name is not valid'
    rescue => e
      ERRORS << e
    end
  ensure
    puts ERRORS
  end
end

但这两种方法都不起作用:


>> user = User.new(:name => 'Shamaoke')
Unknown validator: 'options'
Unknown validator: 'message'

我在哪里以及如何为自定义验证器设置自定义消息?

感谢。

Debian GNU / Linux 5.0.6;

Ruby 1.9.2;

Ruby on Rails 3.0.0。

1 个答案:

答案 0 :(得分:6)

首先,不要include ActiveModel::Validations,它已经包含在ActiveRecord::Base中。其次,您没有使用:options密钥指定验证选项,而是使用验证器的密钥进行验证。

class User < ActiveRecord::Base
  validates :name,
           :is_not_reserved => { :message => 'sorry, but the name is not valid' }
end