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.
/loginto the Sessions controller’s
newaction handles the request and passes it on to the view.
createaction verifies that the user exists in the database. If the user exists, the
createaction 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
In the Sessions controller, add the
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.