诗歌rails之 有条件的validation
默认每次save我们的Model时都会执行validation,但有时候我们希望有一定的条件触发时才执行validation:
- # models/user.rb
- validates_presence_of :password, :if => :should_validate_password?
- validates_presence_of :country, : on => :create
- validates_presence_of :state, :if => :in_us?
- attr_accessor :updating_password
- def in_us?
- country == 'US'
- end
- def should_validate_password?
- updating_password || new_record?
- end
- # in controller
- @user.updating_password = true
- @user.save
莫愁前路无知己,天下无人不识君。