设备中如何更改没有当前密码的密码?

时间:2013-03-26 13:37:34

标签: ruby-on-rails ruby-on-rails-3 devise

我正在devise使用authentication,每个用户都有一个role,我允许admin角色的用户创建新用户,我想要管理员如果用户忘记了密码,则会向其他用户发送edit the password。但是我无法在编辑中没有当前密码的情况下更改密码。那么我如何允许管理员用户通过编辑用户密码来更改密码,并像保存其他值一样保存。

3 个答案:

答案 0 :(得分:12)

由于update_without_password仍然需要current_password来更新密码,因此您必须拥有update这样的内容:

  def update
    # required for settings form to submit when password is left blank
    if params[:user][:password].blank?
      params[:user].delete("password")
      params[:user].delete("password_confirmation")
    end

    @user = User.find(current_user.id)
    if @user.update_attributes(params[:user])
      set_flash_message :notice, :updated
      # Sign in the user bypassing validation in case his password changed
      sign_in @user, :bypass => true
      redirect_to after_update_path_for(@user)
    else
      render "edit"
    end
  end

此示例用于更新当前用户(包括用户密码),但您可以对其进行修改以满足您的需求。

答案 1 :(得分:3)

@user.update_attributes(password: params[:user][:password])

答案 2 :(得分:2)

内置了一个名为update_without_password的方法。

以下是我在更新方法中使用的内容:

 # PUT /manage_users/1
  # PUT /manage_users/1.json
  def update
    @user = User.find(params[:id])
    able_to_edit_profile?

    # required for settings form to submit when password is left blank
    if params[:user][:password].blank?
      params[:user].delete("password")
      params[:user].delete("password_confirmation")
    end

    respond_to do |format|
      if @user.update_attributes(params[:user])
        @user.save        

        # sign the user in with their new password so it doesn't redirect to the login screen
        sign_in @user, :bypass => true

        format.html { 
          flash[:notice] = 'User was successfully updated.'
          redirect_to session.delete(:return_to)
        }
        format.json { head :no_content }
      else
        format.html { render action: "edit", notice: 'Error updating user.' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

private 

  # If the user is not an admin and trying to edit someone else's profile, redirect them
  def able_to_edit_profile?
    if !current_user.try(:admin?) && current_user.id != @user.id
      flash[:alert] = "That area is for administrators only."
      redirect_to :root
  end
  end