Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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])

TY :)

like image 445
stewart715 Avatar asked Jan 19 '23 22:01

stewart715


1 Answers

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.

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:

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. 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):

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. 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:

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!

like image 53
coreyward Avatar answered Jan 30 '23 00:01

coreyward