2010-09-12 133 views
2

我希望能够在模型验证器方法中设置自定义消息,以通知用户有关错误的输入数据。Ruby on Rails。自定义验证器方法中的自定义消息

首先,我设置自定义验证类,其中我重新定义以这种方式的validate_each方法,因为它recommended in rails' documentation

 

# 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。

回答

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 
+0

谢谢,塞缪尔。有用! – Shamaoke 2010-09-13 13:57:37

+0

它不是更清洁? :) – 2010-09-14 11:34:56