Is Ruby on rails a global variable?

I am trying to set the current user to a variable to display "Logged as Joe" on every page. Not quite sure where to start ...

Any quick tips? In particular, which file should have something like this ...

My current user can be defined as (I think): User.find_by_id(session[:user_id])

TY :)

+4
source share
3 answers

You might want to use something like Authlogic or Devise to handle this, rather than rewinding your own auth system, especially if you are not very familiar with the design patterns common in Rails applications.

However, if you want to do what you ask in the question, you should probably define a method in your ApplicationController, for example:

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

You inherit your ApplicationController on all of your regular controllers, so they all have access to the current_user method. In addition, you may need to access the method as an assistant in your views. Rails takes care of you with this too (also in your ApplicationController):

 helper_method :current_user def current_user ... 

Note. If you use find_by_x methods, they raise an ActiveRecord :: RecordNotFound error if nothing is returned. You probably don't want this, but you might want something to prevent users from accessing resources only for users, and again, with 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 

Hooray!

+9
source

It belongs to your controllers.

0
source

All your Application Controller inheirit controllers are for this reason. Create a method in your application controller that returns everything you need, and then you can access it in any of your other controllers.

0
source

All Articles