2010-09-12 160 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