Search code examples
ruby-on-railstwitter-bootstrapruby-on-rails-4redirecttoaction

Trying to "redirect_to :back" after logging in


I'm trying to redirect to the previous page after a user logs in. I am using a bootstrap modal for login/register forms but if someone doesn't have JS enabled on their browser and are taken to the '/login' page, I want to make sure they are redirected to the root url. I know current_page? does not work with POST requests.

I've tried tons of things so the following code is redirecting correctly from the '/login' page to the root url but I am not being redirected to ':back' when logging in using the bootstrap modal.

This is from SessionsController: (PS- I have sessions#new/sessions#create as /login in routes)

def create
    user = User.find_by(email: params[:email]) 
    if user && user.authenticate(params[:password])
        session[:user_id] = user.id

            if request.path === '/login'
                redirect_to '/'
            else
                redirect_to :back
            end

            flash[:success] = "Logged in."

    else
        flash.now[:danger] = "Email and password did not match. Please try again."
        render :new
    end
end

def destroy
    session[:user_id] = nil
    flash[:success] = "Logged out."
    redirect_to '/'
end

Routes.rb:

Rails.application.routes.draw do

root to: 'home#home'

resources :users

get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'

end

Solution

  • Alright I figured it out.

    Routes.rb

    Rails.application.routes.draw do
    
    root to: 'home#home'
    
    resources :users
    
    get '/login', to: 'sessions#new', as: 'login'
    post '/login', to: 'sessions#create'
    get '/logout', to: 'sessions#destroy'
    
    end
    

    SessionsController.rb

    class SessionsController < ApplicationController
    
    def new
    end
    
    def create
        user = User.find_by(email: params[:email]) 
        if user && user.authenticate(params[:password])
            session[:user_id] = user.id
    
                if request.referrer == login_url
                    redirect_to root_path
                else
                    redirect_to :back
                end
    
                flash[:success] = "Logged in."
    
        else
            flash.now[:danger] = "Email and password did not match. Please try again."
            render :new
        end
    end
    
    def destroy
        session[:user_id] = nil
        flash[:success] = "Logged out."
        redirect_to root_path
    end
    
    end
    

    So if the user logs in using the Bootstrap Modal while on any other page than the login_url, they will be redirected back to the current page they were on. If they log in from the actual login page then they will be redirected to root_path.