简体   繁体   English

Ruby on rails全局变量?

[英]Ruby on rails global variable?

I'm trying to set the current user into a variable to display "Logged in as Joe" on every page. 我正在尝试将当前用户设置为变量,以在每个页面上显示“以Joe身份登录”。 Not really sure where to begin... 不确定从哪里开始......

Any quick tips? 任何快速提示? Specifically, what file should something like this go in... 具体来说,这样的文件应该是什么...

My current user can be defined as (I think): User.find_by_id(session[:user_id]) 我当前的用户可以定义为(我认为): User.find_by_id(session[:user_id])

TY :) TY :)

You might want to use something like Authlogic or Devise to handle this rather than rolling your own auth system, especially when you aren't very familiar with the design patterns common in Rails applications. 您可能希望使用Authlogic或Devise之类的东西来处理这个问题,而不是滚动自己的auth系统,尤其是当您不熟悉Rails应用程序中常见的设计模式时。

That said, if you want to do what you're asking in the question, you should probably define a method in your ApplicationController like so: 也就是说,如果你想在问题中做你想要的,你应该在你的ApplicationController中定义一个方法,如下所示:

def current_user
  @current_user ||= User.limit(1).where('id = ?', session[:user_id])
end

You inherit from your ApplicationController on all of your regular controllers, so they all have access to the current_user method. 您从所有常规控制器上的ApplicationController继承,因此它们都可以访问current_user方法。 Also, you might want access to the method as a helper in your views. 此外,您可能希望在视图中将该方法作为帮助程序进行访问。 Rails takes care of you with that too (also in your ApplicationController): Rails也会照顾你(也在你的ApplicationController中):

helper_method :current_user
def current_user ...

Note: If you use the find_by_x methods they will raise an ActiveRecord::RecordNotFound error if nothing is returned. 注意:如果使用find_by_x方法,如果没有返回任何内容,它们将引发ActiveRecord :: RecordNotFound错误。 You probably don't want that, but you might want something to prevent non-users from accessing user only resources, and again, Rails has you covered: 您可能不希望这样,但您可能想要一些东西来阻止非用户访问仅用户资源,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

Cheers! 干杯!

它属于您的控制器。

All your controllers inheirit from Application Controller for exactly this reason. 正是出于这个原因,所有控制器都来自Application Controller。 Create a method in your Application Controller that returns whatever you need and then you can access it in any of your other controllers. 在Application Controller中创建一个返回所需内容的方法,然后您可以在任何其他控制器中访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM