如果用户登录后,我如何保证用户只访问我的网络应用中的路由?我已经有用户和会话模型,用户可以创建帐户。但是,我如何确保如果他们没有登录,他们总是被重定向到登录/注册页面,但如果他们是,他们可以访问所有路由?
编辑:这就是我的应用程序控制器现在的样子:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
因此,如果没有当前用户,我想只允许访问我的Pages控制器及其操作(基本上是home,注册,登录等)。另一方面,如果有用户,我希望该用户能够访问我的路由文件中的所有路由。
答案 0 :(得分:1)
class SomeController < ApplicationController
def show
if current_user.nil?
redirect_to '/path/to/login'
end
end
end
如果你粘贴一些代码,可能会给出一个更详细的答案,否则我们只是猜测你的方法被调用了什么。
答案 1 :(得分:1)
如果您正在使用devise,它会附带内置帮助程序方法 authenticate_user!,该方法应放在您的应用程序控制器中。
如果您没有使用设计,您可以在应用程序控制器中定义您自己的方法(对于此示例,我将复制设计) authenticate_user!并调用之前的操作
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
hide_action :current_user
private
def authenticate_user!
redirect_to :root if current_user.nil?
end
end