-1
class ApplicationController < ActionController::Base

  private

  # Finds the User with the ID stored in the session with the key
  # :current_user_id This is a common way to handle user login in
  # a Rails application; logging in sets the session value and
  # logging out removes it.
  def current_user
    @_current_user ||= session[:current_user_id] &&
      User.find_by_id(session[:current_user_id])
  end
end

How to understand the code above? What does ||= mean? And is @_current_user an id or a user object? Also, why it starts with _?

Can anyone answer me what @_current_user is?

sawa
  • 165,429
  • 45
  • 277
  • 381
OneZero
  • 11,556
  • 15
  • 55
  • 92
  • That post's answer is not good. And it does not answer my other questions about `@_current_user`. – OneZero Mar 31 '13 at 00:18
  • http://stackoverflow.com/questions/8506257/operator-in-ruby - search for "ruby operators". –  Mar 31 '13 at 00:22

1 Answers1

1

Per this question, a ||= b is shorthand for a || a = b.

And regarding the value of @_current_user, if we assume session[:current_user_id] is 5, then the && operator with the User model will return the User instance:

> 5 && User.new(:name => 'Foo')
=> #<User name="Foo"> 

So @_current_user will be the User instance.

Community
  • 1
  • 1
Stuart M
  • 11,458
  • 6
  • 45
  • 59
  • in simply says, it just fetches data from the database to avoid hitting the database again and again for each request, we just decide if @_currentuser already fetched just return, if not go and just fetch and return. – Mooventhan Sep 18 '21 at 16:09