4

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

3 Answers 3

9

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!

Sign up to request clarification or add additional context in comments.

Comments

0

It belongs in your controllers.

2 Comments

is there a single global variable I can set once or do I need to set this in every one of my controllers?
masedesign: If you define a variable in different places, it's not a global variable. Since all your other controllers inherit from your ApplicationController, you can define a class variable in ApplicationController (something like @@foo = 42), and then read it and set it in the other controllers. It won't be a global variable, but if needed only by the controllers, close enough.
0

All your controllers inheirit from Application Controller for exactly this reason. Create a method in your Application Controller that returns whatever you need and then you can access it in any of your other controllers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.