开发者

ActiveRecord bug? Or am I getting it wrong? (validates_presence_of if)

开发者 https://www.devze.com 2022-12-28 12:22 出处:网络
Ok: User attr_accessible :name, :email, :email_confirmation validates_presence_of :email_confirmation if :email_changed?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消