简体   繁体   中英

Rails 3 w/ Devise: How to set two separate homepages based on whether the user is authenticated or not?

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 !!!

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

root to: "dashboard#index", constraints: lambda { |r| r.env["warden"].authenticate? }
root to: "homepage#index"

In your HomeController:

def index
  if !user_signed_in?
    redirect_to :controller=>'dashboard', :action => 'index'
  end
end

(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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM