Now that users can sign up for a new account, let’s add the ability to log in and log out of the app. Using the request/response cycle as a guide again, here’s how logging in and logging out fits in.

Turn one:

  1. When the user visit the login page, the browser makes a GET request for the URL /login.
  2. The Rails router maps the URL /login to the Sessions controller’s new action. The new action handles the request and passes it on to the view.
  3. The view displays the login form.

Turn two:

  1. When the user fills in and submits the form, the browser sends the data via a POST request to the app.
  2. The router maps the request to the Sessions controller’s create action.
  3. The create action verifies that the user exists in the database. If the user exists, the create action logs the user in by creating a new session. Otherwise, it reloads the login page.



Let’s begin by adding a login page. Looking at the request/response cycle, we need five parts to add login machinery to the app: a model, a controller, routes, views, and logic for sessions. As we already created the User model when building the signup page, let’s start here by creating a controller.

Generate a controller named Sessions.


In the routes file, create a route that maps requests for the URL ‘/login’ to the Sessions controller’s new action.


In the Sessions controller, add the new action

def new end

Then in app/views/sessions/new.html.erb, on line 7, use form_for to create a login form:

<%= form_for(:session, url: login_path) do |f| %> <%= f.email_field :email, :placeholder => "Email" %> <%= f.password_field :password, :placeholder => "Password" %> <%= f.submit "Log in", class: "btn-submit" %> <% end %>

We’ve also provided CSS in app/assets/css/application.css.


Restart the Rails server and visit http://localhost:8000/login in the browser.

The form won’t work just yet. We’ll finish it up next.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?