Rails 3 w/ Devise: How to set two separate homepag

2019-03-10 06:15发布

问题:

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

回答1:

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

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


回答2:

In your HomeController:

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


回答3:

(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



回答4:

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