`

RAILS有条件的校验

阅读更多
rails中所有的验证声明都可以接受 :if 选项,可以指定一段在校验之前执行的代码

比如 只有在邮箱地址不为空的时候才验证邮箱地址的格式
使用proc对象,调用时,传入当前的模型对象作为参数,代码返回false时,不做校验
  
validates_format_of :email,
    :with=>/^([A-Za-z0-9_]+)([\.\-\+][A-Za-z0-9_]+)*(\@[A-Za-z0-9_]+)([\.\-][A-Za-z0-9_]+)*(\.[A-Za-z0-9_]+)$/,
    :if=>Proc.new{|u|!u.email.blank?}


一定范围内的“不可重复”校验
比如一个人的**东西,不能重名
  validates_uniqueness_of :name,:scope=>"creator_id"


其他方法,参考如下文章
http://hideto.iteye.com/blog/107829
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics