rails g sessions controller in rails code example

Example 1: rails g sessions controller in rails

Rails.application.routes.draw do
  resources :sessions, only: [:create]
end

Example 2: rails g sessions controller in rails

class SessionsController < ApplicationController
  def create
    user = User
            .find_by(email: params["user"]["email"])
            .try(:authenticate, params["user"]["password"])

    if user
      session[:user_id] = user.id
      render json: {
        status: :created,
        logged_in: true,
        user: user
      }
    else
      render json: { status: 401 }
    end
  end
end

Tags:

Misc Example