Search code examples
ruby-on-railsvalidationnomethoderrorpassword-confirmation

Undefined method password_changed? Error


I'm trying to set my program so that the password only is validated if it is changed (so a user can edit other information without having to put in their password).

I am currently getting an error that says

NoMethodError in UsersController#create, undefined method `password_changed?' for #<User:0x00000100d1d7a0>

when I try to log in.

Here is my validation code in user.rb:

    validates :name,  :presence => true,
 :length   => { :maximum => 50 }
validates :email, :presence   => true,
:format     => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :password, :presence =>true, :confirmation => true, :length => { :within => 6..40 }, :if=>:password_changed?  

Here is my create method in users_controller.rb:

def create
    @user = User.new(params[:user])
    if @user.save
        sign_in @user
        flash[:success] = "Welcome to the Sample App!"
        redirect_to @user
    else
        @title = "Sign up"
        render 'new'
    end
end

Thank you!


Solution

  • Replace with:

    :if => lambda {|user| user.password_changed? }
    

    I'd do two different validations:

    validates :password, :presence =>true, :confirmation => true, :length => { :within => 6..40 }, :on => :create
    validates :password, :confirmation => true, :length => { :within => 6..40 }, :on => :update, :unless => lambda{ |user| user.password.blank? }