How do these methods work?
current_usermethod 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_userwill store that user; otherwise the user is logged out and
- The line
current_usermethod available in the views. By default, all methods defined in Application Controller are already available in the controllers.
require_usermethod uses the
current_usermethod 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.
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]
before_action command calls the
require_user method before running the index or show actions.
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.