Ruby on Rails Tutorial: How to edit user information without confirming the password

删除回忆录丶 提交于 2019-12-05 15:26:17

On your User model, you probably have something along the lines of:

validates_presence_of :password_confirmation

Add an if clause as follows, that way it only checks for the confirmation when the password is actually being changed:

validates_presence_of :password_confirmation, :if => :password_changed?

To slightly refine Dylan's answer, you need to define that password_changed method which was giving you the error. I used a different name, as I don't care if the password has been changed.

 validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :within => 6..40 },
                       :unless => :already_has_password?

  private

    def already_has_password?
      !self.encrypted_password.blank?
    end

If you are using bcrypt to encrypt the password, here is the code that worked for me on Rails 4

#--Code for User method
validates :password, presence: true, confirmation: true, :unless => :already_has_password?   
#
private
    def already_has_password?
      !self.password_digest.blank?
    end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!