Reputation: 5104
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.
Upvotes: 3
Views: 694
Reputation: 14222
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.
Upvotes: 5