Complete the code to set the user ID in the session after login.
session[:user_id] = [1]We store the logged-in user's ID in the session using user.id to identify the user in future requests.
Complete the code to find the current user from the session.
def current_user @current_user ||= User.find_by(id: [1]) end
The session[:user_id] holds the ID of the logged-in user, so we use it to find the user record.
Fix the error in the logout method to clear the session.
def logout [1] end
To log out, we remove the :user_id key from the session using session.delete(:user_id).
Fill both blanks to check if a user is logged in and redirect if not.
def require_login unless [1] redirect_to [2], alert: "Please log in" end end
We check if current_user exists to confirm login. If not, we redirect to the login_path with an alert.
Fill all three blanks to create a session-based login method.
def login user = User.find_by(email: params[:email]) if user && user.authenticate([1]) session[[2]] = user.[3] redirect_to dashboard_path else flash.now[:alert] = "Invalid email or password" render :new end end
We authenticate the user with params[:password]. Then we store the user's id in session[:user_id] to keep them logged in.