Do instance variables within helper methods persist between each request?

Viewed 290

I'm getting into developing Ruby on Rails apps and found a useful tutorial (Ruby on Rails Tutorial (Rails 5)) by Michael Hartl. I'm in chapter 8 right now, where we are developing a bare, simple login/logout functionality from the ground up.

In the tutorial, a helper module is created to check if a user is logged in already. This is called on each request within the header.html.erb partial, in order to determine which links to show in the header.

module SessionsHelper

  #Logs in the given user
  def log_in(user)
    session[:user_id] = user.id
  end

  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

  def logged_in?
      !current_user.nil?
  end

end

Anyway, the author describes this line is used to prevent having to query the database for the user record each time a request is made (only for the first request if the user is logged on)

@current_user ||= User.find_by(id: session[:user_id])

This makes sense to me, but I notice in the server's console, after each request, the database is still being queried for the user's record as @current_user is always reset to nil. So my question is, is this normal? The @current_user variable isn't persisting between requests so I feel like something is wrong. Thanks :)

1 Answers
Related