4

我正在使用devisefor authentication,我role为每个用户都有一个,我允许具有角色的用户创建新用户,如果他们忘记了密码admin,我希望管理员用户为其余用户创建新用户。edit the password但是我无法在没有当前密码的情况下更改密码。那么我如何允许管理员用户通过编辑用户密码来更改密码并像我们对其余值一样保存。

4

3 回答 3

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

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

于 2013-10-08T19:47:56.367 回答
4
@user.update_attributes(password: params[:user][:password])
于 2014-10-27T07:51:17.050 回答
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
于 2013-03-26T14:00:37.387 回答