5

I don't understand why the following is not working in Rails 3. I'm getting "undefined local variable or method `custom_message'" error.

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

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

I also tried using :message => :custom_message instead as was suggested in rails-validation-message-error post with no luck.

:email_format is a custom validator located in lib folder:

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
4

3 回答 3

2

仅供参考,这就是我认为正在发生的事情。'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。

于 2010-11-06T05:11:44.070 回答
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
于 2010-09-25T20:23:07.650 回答
0

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

于 2010-10-07T00:02:14.837 回答