8

I am using Rails 3 and Devise to create an app where users arrive to the website and are shown a homepage containing a login and a signup form. This page has its own controller ("homepage") so it's route is

root :to => "homepage#index"

I want to display a different homepage if the users are already logged in. This would account to having the root point to

root :to => "dashboard#index"

Is there a way to have a conditional route in routes.rb, that would allow me to check whether the user is authenticated before routing them to one of those homepages?

I tried using the following code but if I'm not logged in, devise asks me to log in, so clearly only the first route works.

authenticate :user do
  root :to => "dashboard#index"
end
  root :to => "homepage#index"

Also, I want the url to point to www.example.com in both cases, so that www.example.com/dashboard/index and www.example.com/homepage/index never appear in the browser.

Thanks a million !!!

Andrei Polmolea
  • 147
  • 1
  • 8

4 Answers4

13

Try this, it's specific to Warden/Devise though.

root to: "dashboard#index", constraints: lambda { |r| r.env["warden"].authenticate? }
root to: "homepage#index"
Bradley Priest
  • 7,368
  • 1
  • 26
  • 33
5

In your HomeController:

def index
  if !user_signed_in?
    redirect_to :controller=>'dashboard', :action => 'index'
  end
end
Nicolas Garnil
  • 6,146
  • 3
  • 33
  • 48
  • thanks for the reply @negarnil. The thing is, I tried this option but it does not rewrite the url. I want www.example.com to point to both pages so that www.example.com/dashboard/index is never shown – Andrei Polmolea Jan 17 '12 at 00:47
  • Try render :action => 'dashboard.html.erb. http://guides.rubyonrails.org/layouts_and_rendering.html#wrapping-it-up – Nicolas Garnil Jan 17 '12 at 01:20
2

(Exact same question answered here: https://stackoverflow.com/a/16233831/930038. Adding the answer here too for others' reference.)

In your routes.rb :

authenticated do
  root :to => 'dashboard#index'
end

root :to => 'homepage#index'

This will ensure that root_url for all authenticated users is dashboard#index

For your reference: https://github.com/plataformatec/devise/pull/1147

Community
  • 1
  • 1
pungoyal
  • 1,706
  • 15
  • 17
  • In Rails 4 this does not work. You have to rename one of the two Routes. See my [answer](http://stackoverflow.com/a/19090936/1836143). – Alexander Sep 30 '13 at 09:38
2

Here's the correct answer with rails 4

root to: 'dashboard#index', constraints: -> (r) { r.env["warden"].authenticate? },
         as: :authenticated_root
root to: 'homepage#index'

I tried to add this to / edit the accepted answer but it's too much of an edit to be accepted apparently. Anyway, vote for the accepted answer (from Bradley), it helped me come up with this one :)

Arnaud
  • 15,630
  • 9
  • 57
  • 78