我是Ruby on Rails上的新手,我不使用诸如Cancanca或Devise之类的宝石。
假设我有一个用户登录,但他既没有登录,也没有关闭浏览器。当该用户未登录时,问题是,他仍然可以看到并访问登录页面。我想在他在此页面上时将他重定向到其他地方。我有一个可以检查登录状态的功能。
def authenticate_user!
if logged_in?
else
redirect_to root_path, :notice => ''
end
end
class UsersController < ApplicationController
before_action :authenticate_user!
这两件事可以保证,如果未登录用户,他将被定向到根页。我试图放
def authenticate_user!
if logged_in?
redirect_to current_user
else
redirect_to root_path, :notice => ''
end
end
Rails向我抛出了一个错误,他不认识用户。但是,我也将Current_user定义为同一助手。
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
有人可以帮忙吗?非常感谢
更新:问题解决了:由于我有两个控制器,因此为了避免使用路线永远循环,我将功能分开。检查未登录并为用户控制器提供路由,因此,如果未登录,该页面将登录控制器。检查登录在控制器中的登录和路由登录。
def authenticate_user!
if !logged_in?
redirect_to root_path, :notice => ''
end
end
def authenticate!
if logged_in?
redirect_to current_user
end
end
如果您的Users
控制器并正确设置了视图,则应该能够redirect_to user_path
。
前进,如果您不确定特定路径,则可以在终端中键入rake routes
,它将为您提供所有已知路由的列表。然后,您只需要在"前缀"末端附加_route
或_url
即可。密切注意多元化