Skip to Content
Learn
Authentication
Login II

Well done!

  1. When you visit the URL /login, the browser makes a GET request for the URL. This request hits the Sessions controller’s new action, which returns a view displaying the login page.
  2. In the login form, we use form_for(:session, url: login_path) do |f|. This refers to the name of the resource and corresponding URL. In the signup form, we used form_for(@user) do |f| since we had a User model. For the login form, we don’t have a Session model, so we refer to the parameters above.

Instructions

1.

Next, let’s take in data submitted through the form and log the user in by starting a new session.

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

post 'login' => 'sessions#create'
2.

In the Sessions controller, add the create action

def create @user = User.find_by_email(params[:session][:email]) if @user && @user.authenticate(params[:session][:password]) session[:user_id] = @user.id redirect_to '/' else redirect_to 'login' end end
3.

Visit http://localhost:8000/login and log in with your email and password.

Folder Icon

Sign up to start coding

Already have an account?