Devise 3 (rails 4) can't update user without password

前端 未结 7 1103
萌比男神i
萌比男神i 2021-02-06 00:34

I\'m trying to update a user without having to provide a password, but approaches that worked on older devise/rails versions no longer work with devise 3 and rails 4 strong para

7条回答
  •  野的像风
    2021-02-06 01:21

    You can use @user.update_without_password(user_params) method to update your other fields.

    For example, I have this in my custom users_controller.rb. I update with remote call (ajax).

    #users_controller.rb
    
    def update
      respond_to do |format|
        if needs_password?(@user, user_params)
          if @user.update_with_password(user_params_password_update)
            flash[:success] = 'User was successfully updated. Password was successfully updated'
            format.js {render 'update'}
          else
            error = true
          end
        else
          if @user.update_without_password(user_params)
            flash[:success] = 'User was successfully updated.'
            format.js {render 'update'}
          else
            error = true
          end
        end
    
        if error
          flash[:error] = @user.errors.full_messages.join(', ')
          format.js {render json: @user.errors.full_messages, status: :unprocessable_entity}
        end
      end
    end
    
    private
    
    def needs_password?(user, user_params)
      !user_params[:password].blank?
    end
    
    def user_params
      params[:user].permit(:email, :password, :password_confirmation, :username, :full_name)
    end
    
    #Need :current_password for password update
    def user_params_password_update
      params[:user].permit(:email, :password, :password_confirmation, :current_password, :username, :full_name)
    end
    

提交回复
热议问题