Challenge 2: SessionsController — Solution # app/controllers/sessions_controller.rb class SessionsController < ApplicationController def new end def create @user = User.find_by(email: params[:email]) if @user&.authenticate(params[:password]) session[:user_id] = @user.id redirect_to root_path else render :new, status: :unprocessable_entity end end def destroy session[:user_id] = nil redirect_to root_path end end =begin Notes: - new has an empty body -- it exists purely to implicitly render app/views/sessions/new.html.erb (the login form), following Course 1 Chapter 3's implicit rendering convention. - @user&.authenticate(params[:password]) uses safe navigation: if User.find_by finds no matching email, @user is nil, and &. short- circuits to nil instead of raising NoMethodError trying to call .authenticate on nil. - On success, session[:user_id] = @user.id stores the reference in the encrypted session cookie; on logout, setting it back to nil effectively ends the session -- current_user (Challenge 3) would then find no matching id and return nil again. - render :new, status: :unprocessable_entity on failed login re-displays the login form with a non-2xx status code, rather than silently succeeding or crashing. =end