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

前端 未结 7 1111
萌比男神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:22

    The key is in this "user_params[:password].blank?". The next is a example of the code:

    def update
      if user_params[:password].blank?
        params = user_params_without_password
      else
        params = user_params
      end
    
      respond_to do |format|
        if @user.update(params)
          format.html { redirect_to @user, notice: t(:user_update) }
          format.json { render :show, status: :ok, location: @user }
        else
          format.html { render :edit }
          format.json { render json: @user.errors, status: :unprocessable_entity }
        end
      end
    end
    
    private
    
    def set_user
      @user = User.find(params[:id])
    end
    
    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:email, :username, :first_name, :last_name, :admin, :locked, :password)
    end
    
    def user_params_without_password
      params.require(:user).permit(:email, :username, :first_name, :last_name, :admin, :locked)
    end
    

    Hope you help

提交回复
热议问题