3

I have seen the or equals ||= often used in application controller methods to set a variable if it doesn't exist. The most recent in Railscasts 270. But I have a question.. take for example this helper method

def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

From my understand @current_user is set if it doesn't already exist. This means that rails doesn't have to go out to the database, performance win, etc.

However I'm confused as to the scope of @current_user. Lets say we have two users of our website. The first one (lets call him "bob") comes to the site and sets @current_user to be his user object. Now when the second one ("john") comes in and rails asks for @current_user... why isn't the user object still bob's? After all @current_user was already set once when bob hit the site so the variable exists?

Confused.

Msencenb
  • 5,407
  • 11
  • 48
  • 81

1 Answers1

5

Variables prefixed with @ are instance variables (that is, they are variables specific to a particular instance of a class). John's visit to the site will be handled by a separate controller instance, so @current_user will not be set for him.

cam
  • 13,742
  • 1
  • 40
  • 28
  • Actually one more question. If you are going to use rails low level caching for an instance variable (sql query) does that cache span controller instances? – Msencenb Jul 28 '11 at 21:29
  • @Msencenb: sorry, I'm not sure which kind of caching you are referring to. I am mostly only familiar with view caching as described in the Rails caching guide. – cam Jul 28 '11 at 22:03
  • Perhaps what you are looking for is a class variable (e.g. `@@variable`) which spans all instances of an object. – Karl Jul 28 '11 at 22:20