Rails validate 关于ActiveRecord 的输入检查

通常情况下,如果我们有一个小需求要检查用户在注册的时候输入的用户名是不是重复,那么,我们会怎么做呢。应该比较大众的做法是:

validates_uniqueness_of :name


这是没有问题的,但是,在类级别的定义验证检查通常并不是好办法。例如,你希望能够加一个友好的错误提示并给一个链接如下:

validates_uniqueness_of :name, :message => "The name {{value}} is taken. <a href="/login">Log in</a> instead?"


类级别这样定义的不好如下:
[quote]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.
[/quote]
放到示例里就应该这样:

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值