Learn
Authentication
Filters

How do these methods work?

  1. 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 be nil.
  2. The line helper_method :current_user makes current_user method available in the views. By default, all methods defined in Application Controller are already available in the controllers.
  3. The require_user method uses the current_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

1.

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.

2.

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 %>
3.

Log out of the app, and then visit http://localhost:8000/albums in the browser. You should be redirected to the login page.

4.

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.

Folder Icon

Sign up to start coding

Already have an account?