Ruby on Rails, Devise gem. How to remove current password when password is blank?

后端 未结 2 1930
情深已故
情深已故 2021-02-09 19:24

Now I realise this topic has been covered many times before. However there did not appear to be a solution that wanted to make the current password field exempt only when the pa

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-09 19:28

    Okay so I have finally figured this out!

    Add the following to your class RegistrationsController < Devise::RegistrationsController

    def update
      if resource.update_with_password(params[resource_name])
        set_flash_message :notice, :updated
        sign_in resource_name, resource, :bypass => true
        redirect_to after_update_path_for(resource)
      else
        clean_up_passwords(resource)
        render_with_scope :edit
      end
    end
    

    Then the following to your User model:

    def update_with_password(params={})
      current_password = params.delete(:current_password) if !params[:current_password].blank?
    
      if params[:password].blank?
        params.delete(:password)
        params.delete(:password_confirmation) if params[:password_confirmation].blank?
      end
    
      result = if has_no_password?  || valid_password?(current_password)
        update_attributes(params) 
      else
        self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
        self.attributes = params
        false
      end
    
      clean_up_passwords
      result
    end
    
    def has_no_password?
      self.encrypted_password.blank?
    end
    

    The only thing I was slightly confused about is that in the edit view:

    <% if !current_user.has_no_password? %>
    

    I wrapped it in that if, I would have thought it would have been:

    <% if current_user.has_no_password? %>
    

    If anyone can see anything to improve my code or a different, more efficient way let me know!

提交回复
热议问题