Posted By

bordalix on 07/20/07


Tagged

rails conditional validation validations


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

webstic
davidsi


Conditional validations


 / Published in: Rails
 

From railscast #41

  1. class User < ActiveRecord::Base
  2. validates_presence_of :password, :if => :should_validate_password?
  3. validates_presence_of :state, :on => :create
  4. validates_presence_of :state, :if => :in_us?
  5.  
  6. attr_accessor :updating_password
  7.  
  8. def in_us?
  9. country == 'US'
  10. end
  11.  
  12. def should_validate_password?
  13. updating_password || new_record?
  14. end
  15. end
  16.  
  17. # in controller
  18.  
  19. @user.updating_password = true
  20. @user.save
  21.  
  22. @user.save(false) # will avoid any validation in the model

Report this snippet  

You need to login to post a comment.