Ok:
User
attr_accessible :name, :email, :email_confirmation
validates_presence_of :email_confirmation if :email_changed?
What happens in the following situation:
u = User.find 1
u.name = 'Fonzi'
u.name_changed? # => true
u.email_changed? # => false
u.开发者_开发知识库valid? # => false : email_confirmation is required
Basically, if I change if to unless the validates works as expected, won't validate if the email has not changed, will validate if the email changed. I thought the IF indicates "run this validation if the following function returns true. Seems to work backwards!? Am I just getting it wrong?
You've got the syntax a little mixed up for conditional validations. Instead of using a regular post-fix conditional like that, you pass the validation method an option called "if" whose value is a method, a proc, or a string. So it should look more like this:
validates_presence_of :email_confirmation, :if => :email_changed?
Check out the documentation for the full scoop.
精彩评论