Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Best way to have two different home pages 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 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.

like image 358
Xaxum Avatar asked Aug 09 '11 15:08

Xaxum


2 Answers

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).

like image 132
Logan Leger Avatar answered Oct 24 '22 20:10

Logan Leger


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
like image 34
Kleber S. Avatar answered Oct 24 '22 20:10

Kleber S.