2011-08-14 68 views
1

我在用於用戶認證的我的Rails 3.0.9應用程序中使用Devise。因爲我想能夠管理用戶,我創建了以下用戶控制器:Rails 3在沒有註銷的情況下設計更新密碼

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 

我這個作品的展示,創建和刪除用戶,但我已經更新密碼時遇到問題。

當我更新當前登錄帳戶的密碼時,它會自動將我註銷。

在控制器我試圖解決這個問題使用:(你可以看到它在上面的代碼)

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

但是,這給了我這個錯誤 - >

undefined method `update_with_password' for nil:NilClass 

我是什麼真正需要的是能夠更新任何賬戶密碼,而無需註銷(因爲管理員可以更改常規用戶密碼)。

回答

8

這是沒有必要寫

這段代碼在控制器

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 

歡呼:)

1

最簡單的繼續如何做到這一點叫

sign_in(current_user, :bypass => true) 

更新後。

這是我的控制器的動作是什麼樣子:

def update_password 
    if current_user.update_with_password(params[:user]) 
    sign_in(current_user, bypass: true) 
    flash[:notice] = "Updated Password Successfully" 
    else 
    flash[:error] = "There was an error updating your password, please try again." 
    end 
end 

我認爲這基本上是什麼@challenge提出,但我只想做一點更清潔和更容易理解。

相關問題