Rails 3 The Best Way to Have Two Different Homepages Based on Login Status

First I tried to access the session variable in the routes.rb file and put a simple if statement. If the user is logged in, go to the input element # index else, go to the index # of the site. However, route.rb does not seem to have access to session variables. I have a [: user_id] session and you can use it to confirm the login status. Is it better to set the page that was logged out as the home page in route.rb, and then redirect to this controller if the user has registered or is there a better way that I don’t know about?

Here is what I did in the controller for the home page with the user disabled.

def index if User.find_by_id(session[:user_id]) redirect_to entry_url end end 

It works great, but not sure if there are any problems with this or the best way. Any thoughts would be appreciated.

+4
source share
2 answers

In fact, routes have access to session variables. You can set a login restriction for logging in with a different root, as shown below:

 # Logged in constraints lambda { |req| !req.session[:user_id].blank? } do root :to => "entry#index", :as => "dashboard" end # Not logged in root :to => "landing#index" 

It is important to note two things: firstly, order matters here; secondly, that the restriction can be reorganized into one line route, if you do not plan to use the restriction further (which I always do).

+7
source

Definitely this should be handled by your controller, not your routes.

 def index @user = User.find_by_id(session[:user_id]) if @user redirect_to entry_url else redirect_to landing_url end end 
+1
source

All Articles