简体   繁体   中英

Redirect root_path in rails for already signed_in user without using Devise

In my application i have root_path root 'home#mainPage' and though a user is signed in , he can accesss http://localhost:3000/ which i dont want. So i am following https://stackoverflow.com/a/8739874/3786657 answer to add this feature and i am getting undefined method user_signed_in? for AuthenticatedUser:Class undefined method user_signed_in? for AuthenticatedUser:Class . I am using Rails 4.2.0

My routes:

  constraints(AuthenticatedUser) do 
    root :to => "users#show", as: :authenticated
  end

  root 'home#mainPage'

Lib/authenticated_user.rb:

class AuthenticatedUser
  def self.matches?(request)
    user_signed_in?
  end
end

application_helper.rb

module ApplicationHelper
    def user_signed_in?
        !!session[:user_id]
    end
    def current_user
        User.find(session[:user_id])
    end
end

Config/application.rb

config.autoload_paths << Rails.root.join('lib')

The user_signed_in? method defined in ApplicationHelper is not available to AuthenticatedUser . Since you can get the session from the request I would just check it directly in AuthenticatedUser :

class AuthenticatedUser
  def self.matches?(request)
    !!request.session[:user_id]
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM