Rails foundationSort Order

Rails: User Sessions

In this episode we show you what to do once we receive the email and the password from the form. We show you how to handle the session if the user entered the email and password correctly, and how to handle the situation if the user entered the wrong credentials.

We'll start off generating our sessions_controller.rb

rails g controller sessions

We'll add the create action but leave it empty for now.

class SessionsController < ApplicationController  def create      endend

We'll also need to generate our view.

# app/views/sessions/new.html.erb<%= form_tag sessions_path do %>  <div class='form-group'>    <%= label_tag :email %>    <%= text_field_tag :email, nil, class: 'form-control' %>  </div>  <div class='form-group'>    <%= label_tag :password %>    <%= password_field_tag :password, nil, class: 'form-control' %>  </div>  <div class='actions'>    <%= submit_tag "Sign In", class: 'btn btn-success btn-block' %>  </div><% end %>

We should now be able to test out our sign in form. We'll debug the whole proccess so we understand everything that needs to happen in the session create action.

class SessionsController < ApplicationController  def create    @user = User.where(email: params[:email]).first    if @user.authenticate(params[:password])      session[:user_id] = @user.id      redirect_to root_path    else      flash[:error] = "Invalid email or password"      render :new    end  endend

That's pretty much it for the session creation part.