我正在尝试仅在用户更改密码的页面上设置密码确认。 我的模型看起来像这样:
class User < ActiveRecord::Base
attr_accessor :password_confirmation
acts_as_authentic do |c|
c.validate_login_field = false
c.validate_password_field = false
c.require_password_confirmation = true
c.logged_in_timeout(15.minutes)
end
validates :name, :presence => {:message => 'cannot be blank.'}, :allow_blank => true, :length => {:minimum => 3, :maximum => 40}, :on => :create
validates :email, :presence => {:message => 'address cannot be blank.'}, :allow_blank => true, :format => {:with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/, :message => 'address is not valid. Please, fix it.'}, :uniqueness => true
validates :password, :presence => {:message => 'cannot be blank.'}, :allow_blank => true, :length => { :minimum => 6, :maximum => 40}, :on => :create
validates :password_confirmation, :presence => {:message => 'cannot be blank.'}, :allow_blank => true, :length => { :minimum => 6, :maximum => 40 }, :on => :update
end
和我保存新密码的方法:
def change_password
@user = current_user
if @user.valid_password?(params[:user][:old_password])
if @user.update_attributes(params[:user].reject{|key, value| key == "old_password"})
flash[:notice] = 'Your password was successfuly changed.'
redirect_to :back
else
flash[:warning] = 'You did not fill twice your new password correctly. Please, fix it.'
redirect_to :back
end
else
flash[:warning] = 'Your old password is WRONG! What is your malfunction!?!'
redirect_to :back
end
end
我的问题是,如果我将表单设置为旧密码,然后设置新密码(例如 new_password ),然后确认新密码(例如 new_password1 ),所以新密码被更改&amp;保存到数据库中 - 但它不应该,因为新密码和新密码的确认不一样...
我应该如何设置验证规则,或者哪里可能有问题?
感谢您的建议
答案 0 :(得分:1)
只有在密码被更改时才需要验证密码。如果没有更改,则应跳过password
字段的验证。
Railscasts.com episode #41向您展示了如何执行此操作。