通常情况下,如果我们有一个小需求要检查用户在注册的时候输入的用户名是不是重复,那么,我们会怎么做呢。应该比较大众的做法是:
validates_uniqueness_of :name
这是没有问题的,但是,在类级别的定义验证检查通常并不是好办法。例如,你希望能够加一个友好的错误提示并给一个链接如下:
validates_uniqueness_of :name, :message => "The name {{value}} is taken. <a href="/login">Log in</a> instead?"
类级别这样定义的不好如下:
引用
Did you see the use of {{value}} in there? That’s because ActiveRecord’s DSL for validations operates on a class level, and that means that when you are declaring the validation, you don’t have access to the instance you will be dealing with. Note also that there’s HTML in the error message. It’s nice to point the user in the right direction, and here it only makes sense to send the user to the login page. But HTML in the models is wrong in many levels, not to mention that the URL helpers are not available there.
放到示例里就应该这样:
def validate
validates_uniqueness_of :name, :message => "The name #{name} is taken. <a href="/login">Log in</a> instead?"
end
同样的,还可以有如下的例子:
在类里定义的话如下:
validates_presence_of :card_number, :if => :paid_with_card?
def paid_with_card?
payment_type == "card"
end
这时的作用范围会出错,放到示例如下:
def validate
validates_presence_of :card_number if paid_with_card?
end
validates_presence_of :surname, :if => "name.nil?"
def validate
validates_presence_of :surname if name.nil?
end
validates_confirmation_of :password,
:unless => Proc.new { |a| a.password.blank? }
def validate
validates_confirmation_of :password unless password.blank?
end