Rails3 + Devise : prevent password validation when updating

前端 未结 4 1369
Happy的楠姐
Happy的楠姐 2021-01-01 00:23

I\'ve looking for a way to allow users to change their settings (User model) without having to change their password (they still have to enter their current password). Devis

4条回答
  •  盖世英雄少女心
    2021-01-01 01:03

    I tried Amal Kumar S solution, but unfortunately it didn't help me to solve the same issue, so here is modified version of solution tested in real project.

    Here is the code from devise/models/validatable.rb module

    protected
    
    # Checks whether a password is needed or not. For validations only.
    # Passwords are always required if it's a new record, or if the password
    # or confirmation are being set somewhere.
    def password_required?
      !persisted? || !password.nil? || !password_confirmation.nil?
    end
    

    The validation fails when you leave blank password and password confirmation fields while updating user info, because this condition is always false:

    !password.nil? || !password_confirmation.nil? 
    

    Password and password_confirmation fields equals blank string '' which is never equals to nil. So you can fix that by overriding password_required? method in your user model and change nil? check to blank? check.

    protected
    
    def password_required?
     !persisted? || !password.blank? || !password_confirmation.blank?
    end
    

    Think that it's easiest way to fix that and it's doesn't ruin original logic. Maybe it's devise's bug.

提交回复
热议问题