title: Ruby on Rails session[:user_id] not being set properly
body: <p>I Created a login controller where once a user is logged in, he will be directed to his home page. As shown below, I'm setting the session variable in the login controller. In the application controller I have current user methods which will check whether a user exists for the currently logged in key. Although I log in successfully, If i use later the 'current_user method' given in ApplicationController, It redirects me to the login page as the current_user is a nil object. Does any one have any idea as to where I went wrong.</p>
  
  <pre><code>class User::Signin::LoginController &lt; ApplicationController
  
  def login
  render('/login')
  end
  
  def attempt_login
      @user = User.find_by_email(params[:user][:email])
      if @user &amp;&amp; @user.authenticate(params[:user][:password])
        session[:user_id] = @user.id
        flash[:notice] = "You are now logged in"
  
  
        if @user.role == 1
  
          redirect_to controller: '/patient/home', action: 'show', :id =&gt; @user.patient_id
        end
  
        if @user.role ==2
          redirect_to controller: '/doctor/home', action: 'show', :id =&gt; @user.doctor_id
        end
  
        if @user.role ==3
          redirect_to controller: '/staff/home', action: 'show', :id =&gt; @user.staff_id
        end
  
  
      else
        flash.now[:notice] = "Invalid username/ password combination."
        render 'login/login'
      end
    end
  
   def logout
      session[:user_id] = nil
      flash[:notice] = 'logged out'
      redirect_to('/login')
    end
  
  end
  </code></pre>
  
  <p>The ApplicationController</p>
  
  <pre><code>class ApplicationController &lt; ActionController::Base
    protect_from_forgery
  
    helper_method :current_user
  
    def current_user
      @current_user ||= User.find_by_id!(session[:user_id]) if session[:user_id]
    end
  
    def require_user
      redirect_to '/login' unless current_user
    end
  
    def require_admin
      redirect_to '/login' unless current_user.admin?
    end
  
    def require_doctor
      redirect_to '/login' unless current_user.doctor?
    end
  
    def require_patient
      redirect_to '/login' unless current_user.patient?
    end
  
    def require_staff
      redirect_to '/login' unless current_user.staff?
    end
  
    private
    def confrim_logged_in
      unless session[:user_id]
        flash[:notice] = "Please log in"
        redirect_to '/login'
      end
    end
  
  
  end
  </code></pre>
  
  <p>Usage of current_user</p>
  
  <pre><code>class Patient::HomeController &lt; ApplicationController
    layout 'patient'
    protect_from_forgery
  
    def show
      @patient = Patient.find(params[:id])
      @current_user=current_user
      render('patients/home')
    end
  
  
  end
  </code></pre>