Rails: Detecting User Session
In this episode we show you how to detect the user session so we can have the context of current_user in our application. We will then be able to use the context in our controller and views.
In the application_controller we'll implement the current_user method so we can access it from any other controller that inherits from it.
class ApplicationController < ActionController::Base
# allows us to use the same method in the view
Now in the layout we'll render the email of the user.
<div id='main' class='container'>
<% if current_user %>
# if we have the user session
<%= current_user.email %>
<%= link_to 'Sign Out', sessions_path, method: :delete %>
<% else %>
# if we don't have the user session
<%= link_to 'Sign in', new_session_path %>
<%= link_to 'Sign up', new_user_path %>
<% end %>
<%= yield %>
View wise this should cover most of the functionality of the user authentication process.