模型验证

时间:2011-09-08 09:35:02

标签: ruby-on-rails ruby-on-rails-3 validation model

是否可以检查:password字段中输入的内容是否与模型中的:current_password字段不同?

这样的东西
validates :current_password, :format => { :with => :password, :message => "Current password can't be the same as the password" }

哪种不起作用的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

首先,我希望您不要将密码存储为纯文本

其次,自定义验证适用于您:

validate :password_is_not_the_same

def password_is_not_the_same
  errors.add(:password, 'Current password can\'t be the same as the password') if BCrypt::Password.new(password_digest) == password
end

修改

validate :password_is_not_the_same

def password_is_not_the_same
  errors.add(:password, 'Current password can\'t be the same as the password') if current_password == password
end