Authlogic - 如何仅为更新设置password_confirmation?

时间:2012-04-08 11:48:24

标签: ruby-on-rails-3 passwords authlogic password-confirmation

我正在尝试仅在用户更改密码的页面上设置密码确认。 我的模型看起来像这样:

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;保存到数据库中 - 但它不应该,因为新密码新密码的确认不一样...

我应该如何设置验证规则,或者哪里可能有问题?

感谢您的建议

1 个答案:

答案 0 :(得分:1)

只有在密码被更改时才需要验证密码。如果没有更改,则应跳过password字段的验证。

Railscasts.com episode #41向您展示了如何执行此操作。