ste*_*715 4 ruby ruby-on-rails ruby-on-rails-3
我正在尝试将当前用户设置为变量,以在每个页面上显示"以Joe身份登录".不确定从哪里开始......
任何快速提示?具体来说,这样的文件应该是什么...
我当前的用户可以定义为(我认为): User.find_by_id(session[:user_id])
TY :)
您可能希望使用Authlogic或Devise之类的东西来处理这个问题,而不是滚动自己的auth系统,尤其是当您不熟悉Rails应用程序中常见的设计模式时.
也就是说,如果你想在问题中做你想要的,你应该在你的ApplicationController中定义一个方法,如下所示:
def current_user
@current_user ||= User.limit(1).where('id = ?', session[:user_id])
end
Run Code Online (Sandbox Code Playgroud)
您从所有常规控制器上的ApplicationController继承,因此它们都可以访问该current_user方法.此外,您可能希望在视图中将该方法作为帮助程序进行访问.Rails也会照顾你(也在你的ApplicationController中):
helper_method :current_user
def current_user ...
Run Code Online (Sandbox Code Playgroud)
注意:如果使用find_by_x方法,如果没有返回任何内容,它们将引发ActiveRecord :: RecordNotFound错误.您可能不希望这样,但您可能想要一些东西来阻止非用户访问仅用户资源,Rails再次为您提供:
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
before_filter :require_user
private
def current_user
@current_user ||= User.limit(1).where('id = ?', session[:user_id])
end
def require_user
unless current_user
flash[:notice] = "You must be logged in to access this page"
redirect_to new_session_url
return false
end
end
end
Run Code Online (Sandbox Code Playgroud)
干杯!