未定义的方法password_changed?错误

ste*_*392 8 validation ruby-on-rails password-confirmation nomethoderror

我正在尝试设置我的程序,以便仅在密码更改时验证密码(这样用户可以编辑其他信息而无需输入密码).

我目前收到错误消息

NoMethodError in UsersController#create, undefined method `password_changed?' for #<User:0x00000100d1d7a0>
Run Code Online (Sandbox Code Playgroud)

当我尝试登录时

这是我的验证码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?  
Run Code Online (Sandbox Code Playgroud)

这是我的创建方法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
Run Code Online (Sandbox Code Playgroud)

谢谢!

apn*_*ing 5

用...来代替:

:if => lambda {|user| user.password_changed? }
Run Code Online (Sandbox Code Playgroud)

我会做两种不同的验证:

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? }  
Run Code Online (Sandbox Code Playgroud)