Conditional validations


/ Published in: Rails
Save to your folder(s)

From railscast #41


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.