我试图仅在用户更改密码的页面上设置密码确认。我的模型看起来是这样的:
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),所以新密码被更改并保存到数据库中 - 但它不应该,因为新密码和新密码的确认不一样……
我应该如何设置验证规则,或者哪里可能出现问题?
感谢您的建议