How do these methods work?
- The
current_user
method determines whether a user is logged in or logged out. It does this by checking whether there’s a user in the database with a given session id. If there is, this means the user is logged in and@current_user
will store that user; otherwise the user is logged out and@current_user
will benil
. - The line
helper_method :current_user
makescurrent_user
method available in the views. By default, all methods defined in Application Controller are already available in the controllers. - The
require_user
method uses thecurrent_user
method to redirect logged out users to the login page.
Read more about the ||=
syntax in this Stack Overflow post.
For more insight into using the unless
keyword, read this blog post.
Instructions
Let’s use require_user
in the Albums controller in order to prevent logged out users from accessing these pages. In the Albums controller, add this as the first line inside the class:
before_action :require_user, only: [:index, :show]
The before_action
command calls the require_user
method before running the index or show actions.
Let’s use current_user
in application layout to update the nav items depending on whether a user is logged in or out. In app/views/layouts/application.html.erb, within <div class="nav pull-right">
, add the following code:
<% if current_user %> <ul> <li><%= current_user.email %></li> <li><%= link_to "Log out", logout_path, method: "delete" %></li> </ul> <% else %> <ul> <li><%= link_to "Login", 'login' %></a></li> <li><%= link_to "Signup", 'signup' %></a></li> </ul> <% end %>
Log out of the app, and then visit http://localhost:8000/albums
in the browser. You should be redirected to the login page.
Log in to the app with your email and password, and then visit http://localhost:8000/albums
. You should now be able to access it.