诗歌rails之 有条件的validation

默认每次save我们的Model时都会执行validation,但有时候我们希望有一定的条件触发时才执行validation:
Java代码
  1. # models/user.rb  
  2. validates_presence_of :password, :if => :should_validate_password?  
  3. validates_presence_of :country, : on => :create  
  4. validates_presence_of :state, :if => :in_us?  
  5. attr_accessor :updating_password  
  6.   
  7. def in_us?  
  8.   country == 'US'  
  9. end  
  10.   
  11. def should_validate_password?  
  12.   updating_password || new_record?  
  13. end  
  14.   
  15. # in controller  
  16. @user.updating_password = true  
  17. @user.save  
posted @ 2009-07-09 09:58  麦飞  阅读(171)  评论(0编辑  收藏  举报