2011-08-14 2 views
1

사용자 인증을 위해 레일즈 3.0.9 애플리케이션에서 Devise를 사용하고 있습니다. 나는 사용자를 관리 할 수 ​​있기를 원으로, 나는 다음과 같은 사용자의 컨트롤러 생성 :레일즈 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 @user.update_attributes(params[:user]) 
    sign_in(current_user, :bypass => true) 
    redirect_to users_path 
end 

환호 :

1

가장 쉬운 함께 진행한다 대신

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

컨트롤러에

이 코드를 작성할 필요가 없습니다 이 작업을 수행하는 방법은

입니다. 0
sign_in(current_user, :bypass => true) 

업데이트 후. 나는이 제안하지만 조금 청소기를 만들고 싶어하고 이해하기 쉽게 @challenge 기본적으로 무엇을 생각

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 

:

이처럼 내 컨트롤러 액션 보이는 것입니다.

관련 문제