Pergunta

I want to set the root depending on the cookie/session. If the user is loged in already I want to check on the cookie/session and render a different page accordingly as the root url.

I want to do something like this

if (cookie with userID) do
   root 'user/index'
else
   root 'welcome/index'
end

Is there a way I could access the ApplicationController or something similar so that I could check on everything?

Thanks

Foi útil?

Solução

I think you should use a different approach here. For example, you can map root path always to same action and put all logic into that action:

class UsersController < ApplicationController
  def index
    redirect_to welcome_path and return unless logged_in?
    ... # rest of your code here 
  end
end

NOTE: Assuming logged_in? is a method that loads current user from session or returns nil.

Probably it's a good idea to move this kind of logic into a before_filter (in Rails4 before_action):

class UsersController < ApplicationController
  before_filter :require_login

  def index
  end

  private

  def require_login
    redirect_to welcome_path unless logged_in?
  end
end

If most of your application (controllers scope) depends on a logged user, move it to the ApplicationController (filter will run on each request). You can skip it using skip_before_filter :require_login in the particular cases without this requirement.

By the way, if you want to achieve it via your routes, you can play with constraints (doc here). Example code:

YourApp::Application.routes.draw do
  root 'users#index', constraints: lambda { |request| request.session['user_id'].present? }
  root 'welcome#index'
end

More ideas in this question: How can I redirect a user's home (root) path based on their role using Devise?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top