我在我的 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/