Authlogic - how to set password_confirmation only for update?

784 Views Asked by At

I am trying to set up the password confirmation only on the page, where the user change his password. My model looks this way:

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

and my method that saving new password:

  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

My problem is, that if I set the form the old password, then new password (eg. new_password) and then the confirmations of the new password (eg. new_password1), so the new password is changed & saved into the database - but it shouldn't, because the new password and the confirmation of the new password aren't the same...

How I should set up the validation rules or, where could be a problem?

Thanks for advices

1

There are 1 best solutions below

0
jefflunt On BEST ANSWER

You need to validate the password only if it's being changed. If it's not being changed, then the validation for the password field should be skipped.

Railscasts.com episode #41 shows you how to do this.