title: Rails - Why use self.current_user = user in sign_in method
body: <p>I have finished the <a href="http://ruby.railstutorial.org/ruby-on-rails-tutorial-book" rel="nofollow noreferrer">Ruby on Rails Tutorial</a> by Michael Hartl. I know some basic ideas about instance variable, getters and setters. </p>
  
  <p>The sign_in method is <a href="http://ruby.railstutorial.org/chapters/sign-in-sign-out#code-sign_in_function" rel="nofollow noreferrer">here</a></p>
  
  <pre><code>def sign_in(user)
    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user
  end
  </code></pre>
  
  <p>Now I'm stuck at this line</p>
  
  <pre><code>self.current_user = user
  </code></pre>
  
  <p>I found this related <a href="https://stackoverflow.com/questions/11969935/understand-current-user-concept-when-creating-a-login-session-in-ruby">question</a>, but I still don't get it.</p>
  
  <p>After sign_in, the user will be redirected to another page, so <code>@current_user</code> will be nil. Rails can only get current_user from cookie or session, then set <code>@current_user</code>, so that it doesn't need to check cookie or session again in current request.</p>
  
  <p>In sign_out method</p>
  
  <pre><code>def sign_out
    self.current_user = nil
    cookies.delete(:remember_token)
  end
  </code></pre>
  
  <p>For the same reason, why do we need <code>self.current_user = nil</code> since the user would be redirected to root_url?</p>
  
  <p>Here's the code for getter and setter</p>
  
  <pre><code>def current_user=(user)
    @current_user = user
  end
  
  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end
  </code></pre>