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 entry#index else go to landing#index. However, routes.rb does not seem to have access to session variables. I have session[:user_id] set and can use it to verify login status. Is it best to set the logged out page as home in routes.rb and then redirect in that controller if the user is logged in or is there a better way that I don't know about?
Here is what I did in the controller for the logged out user home page.
def index
if User.find_by_id(session[:user_id])
redirect_to entry_url
end
end
It works fine but not sure if there are any issues with this or a better way. Any thoughts would be appreciated.
The routes actually do have access to session variables. You can set a constraint to route logged in users to a different root like 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's important to note two things: first that the order matters here; second that the constraint can be refactored into a one line route unless you plan to use the constraint further (which I always do).
Definitely it should be handled by your controller and not by 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With