2010-09-20 216 views
5

我不明白为什么以下不在Rails 3中工作。我得到“未定义的局部变量或方法`custom_message'”错误。Rails 3:验证中的自定义错误消息

validates :to_email, :email_format => { :message => custom_message } 

def custom_message 
    self.to_name + "'s email is not valid" 
end 

我也尝试使用:消息=>:自定义信息,而不是如在rails-validation-message-error交没有运气建议。

:email_format是位于lib文件夹一个自定义的验证:

class EmailFormatValidator < ActiveModel::EachValidator 
    def validate_each(object, attribute, value) 
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i 
     object.errors[attribute] << (options[:message] || 'is not valid') 
    end 
    end 
end 
+0

我可以使用您的确切代码复制您的错误,但是当我按照您的建议将其更改为':message =>:custom_message'时,错误消失。 – Dusty 2010-09-25 19:46:26

回答

1

如果有人有兴趣,我想出了下面的解决我的问题:

型号:

validates :to_email, :email_format => { :name_attr => :to_name, :message => "'s email is not valid" } 

lib/email_format_validator.rb:

class EmailFormatValidator < ActiveModel::EachValidator 

    def validate_each(object, attribute, value) 
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i 

     error_message = if options[:message] && options[:name_attr] 
     object.send(options[:name_attr]).capitalize + options[:message] 
     elsif options[:message] 
     options[:message] 
     else 
     'is not valid' 
     end 

     object.errors[attribute] << error_message 
    end 
    end 
end 
0

也许方法“custom_message”需要在验证之上定义。

1

仅供参考,这是我相信正在发生的事情。 'validates'方法是一个类方法,即MyModel.validates()。当你将这些参数传递给'验证'并且你调用'custom_message'时,你实际上调用了MyModel.custom_message。所以你需要像

def self.custom_message 
    " is not a valid email address." 
end 

validates :to_email, :email_format => { :message => custom_message } 

与self.custom_message之前定义的调用来验证。