ruby-on-rails-3 - Rails 3 在不注销的情况下设计更新密码

我在我的 Rails 3.0.9 应用程序中使用 Devise 进行用户身份验证。因为我希望能够管理用户,所以我创建了以下用户 Controller :

class UsersController < ApplicationController
  
  def index
     @users = User.all
   end

   def new
     @user = User.new
   end

   def create
     @user = User.new(params[:user])
     if @user.save
       flash[:notice] = "Successfully created User." 
       redirect_to users_path
     else
       render :action => 'new'
     end
   end

   def edit
     @user = User.find(params[:id])
   end

   def update
     @user = User.find(params[:id])
     params[:user].delete(:password) if params[:user][:password].blank?
     params[:user].delete(:password_confirmation) if params[:user][:password].blank? and params[:user][:password_confirmation].blank?
     if @user.update_attributes(params[:user])
       if current_user.update_with_password(params[:user])
           sign_in(current_user, :bypass => true)
       end
       flash[:notice] = "Successfully updated User."
       redirect_to users_path
     else
       render :action => 'edit'
     end
   end

   def destroy
     @user = User.find(params[:id])
     if @user.destroy
       flash[:notice] = "Successfully deleted User."
       redirect_to users_path
     end
   end
  
end

我这适用于显示、创建和删除用户,但我在更新密码时遇到了问题。

当我更新当前登录帐户的密码时,它会自动注销我。

在 Controller 中,我尝试使用以下方法修复此问题:(您可以在上面的代码中看到它)

if current_user.update_with_password(params[:user])
   sign_in(current_user, :bypass => true)
end

但这给了我这个错误 ->

undefined method `update_with_password' for nil:NilClass 

我真正想要的是无需注销即可更新任何帐户密码的能力(因为管理员可以更改普通用户的密码)。

最佳答案

没必要写

Controller 中的这段代码

if current_user.update_with_password(params[:user])
  sign_in(current_user, :bypass => true)
end

相反,你应该继续下面的内容

if @user.update_attributes(params[:user])
   sign_in(current_user, :bypass => true)
   redirect_to users_path
end

干杯:)

https://stackoverflow.com/questions/7057253/

相关文章:

bash - .bashrc 在云端?

java - 从代数表达式创建二叉树

objective-c - [pool release] 和 [pool drain] 有什么区别?

fonts - Safari 放大/缩小破坏页面布局(不能很好地改变字体大小)

ruby-on-rails - ruby rails : How can I add a css f

oop - R : Use a different base field/corpus 中的运算符重

perl - reverse 不在列表上下文中隐式使用 $_,这是一个错误吗?

function - 为什么 Matlab 看不到我的函数?

amazon-ec2 - 使用pscp自动接受rsa指纹

django - 将 Django 模型/表拆分为两个模型/表是否有性能优势?