2016-11-02 92 views
0

我試圖做以下工作:rails ruby​​ double pipe session

1)如果我是用戶,當我刪除我的帳戶時,我退出登錄。

2)如果我是管理員,當我刪除其他用戶的帳戶時,我保持登錄狀態。

它的工作原理,當我設置CURRENT_USER方法

def current_user 
    @current ||= User.find(session[:user_id]) if session[:user_id] 
    end 

,但是當我將它設置爲

def current_user 
    User.find(session[:user_id]) if session[:user_id] 
    end 

它給了我這個錯誤

ActiveRecord::RecordNotFound in UsersController#destroy 
Couldn't find User with 'id'=30 

我不明白爲什麼「@current || =」讓它工作。

application_controller.rb 

def require_signin 
    unless current_user 
    session[:intended_url] = request.url 
    redirect_to signin_path, notice: "This page requires signin" 
    end 
end 

def require_admin 
    unless current_user_admin? 
    redirect_to root_path, notice: "Unauthorized Access" 
    end 
end 

def current_user_admin? 
    current_user && current_user.admin? 
end 

def current_user 
    @current ||= User.find(session[:user_id]) if session[:user_id] 
end 

def current_user?(user) 
    user == current_user 
end 


user_controller.rb 

def destroy 
    @user = User.find(params[:id]) 
    unless current_user?(@user) || current_user_admin? 
     redirect_to root_path, alert: "Unauthorized Access" 
    end  
    @user.destroy 
    session[:user_id] = nil unless current_user_admin? 
    redirect_to players_path, alert: "'#{@user.name}' was deleted" 
end 

回答

1

||=運算符表示「設置該變量,如果它尚未設置」。

當您刪除當前登錄的帳戶時,將從數據庫中刪除User,但session[:user_id]仍設置爲現在刪除的User的ID。

嘗試撥打User#find並刪除了一個用戶ID將導致ActiveRecord錯誤。

爲什麼這樣做時,||=運營商存在發生的原因是因爲@current變量是已經集因此User#find永遠不會被調用。

# this will only try to call User#find if the @current variable is not already set 
@current ||= User.find(session[:user_id]) 

# this will always attempt to call User#find 
# if session[:user_id] is set to a deleted user's ID it will raise an error 
@current = User.find(session[:user_id]) 
+0

何時@current值被重置? – iswg

+0

這是違規行:'session [:user_id] = nil,除非current_user_admin?'。當你調用'current_user_admin?'時,它調用'current_user',它試圖重置'@ current'變量。如果你刪除了一個'User',你應該始終清除會話。如果session [:id] == params [:id]'可能會嘗試'session [:user_id] = nil'如果ID等於剛剛刪除的用戶的ID,則會清除會話。 –

+0

有沒有辦法讓第二個current_user方法起作用? – iswg