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
何時@current值被重置? – iswg
這是違規行:'session [:user_id] = nil,除非current_user_admin?'。當你調用'current_user_admin?'時,它調用'current_user',它試圖重置'@ current'變量。如果你刪除了一個'User',你應該始終清除會話。如果session [:id] == params [:id]'可能會嘗試'session [:user_id] = nil'如果ID等於剛剛刪除的用戶的ID,則會清除會話。 –
有沒有辦法讓第二個current_user方法起作用? – iswg