13

I want to show different root page for users in Rails.

I defined the root:

root :to => 'welcome#index'

And the welcome control:

class WelcomeController < ApplicationController
  before_filter :authenticate_user!

  def index
  end

end

Currently it is ok for logged in users, but the not logged in users redirected to /users/sign_in

I want to show static root page and not redirect.

Bruce Dou
  • 4,673
  • 10
  • 37
  • 56
  • 1
    Remove your before_filter and add your logic into the index method to determine what to display based on whether they are logged in. Are you using devise? – Marc Talbot Feb 18 '12 at 07:49
  • @MarcTalbot yes, is it possible implement in routes.rb ? – Bruce Dou Feb 18 '12 at 07:51
  • 1
    This exact question has been answered here http://stackoverflow.com/questions/8888289/rails-3-w-devise-how-to-set-two-separate-homepages-based-on-whether-the-user-i/8888513#8888513 – Bradley Priest Feb 18 '12 at 08:09
  • That did not worked. @Bradley – Bruce Dou Feb 18 '12 at 08:13
  • Your routes.rb file has no way of knowing whether your user is authenticated or not. What is not working about putting the logic in the index method of the controller? – Marc Talbot Feb 18 '12 at 13:39
  • If you are using warden, which is what devise is built on, you do actually have access to whether the user is logged in or not in the routes file through env['warden']. – Bradley Priest Feb 18 '12 at 19:01

3 Answers3

25

The answer, suggested by Puneet Goyal will not work in Rails 4. See this. The solution is to use an alias for one of the two routes like this:

authenticated do
  root :to => 'welcome#index', as: :authenticated
end

root :to => 'home#static_page'
Alexander Popov
  • 23,073
  • 19
  • 91
  • 130
2

In your routes.rb :

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

root :to => 'home#static_page'

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

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

pungoyal
  • 1,768
  • 15
  • 17
  • This doesn't work in Rails 4 anymore, try: authenticated :user do root to: 'dashboard#index', as: :authenticated_root end root to: 'landing_page#index', as: :public_root – port5432 Nov 10 '15 at 10:40
2

This answer should work. This was posted on the page Bradley linked.

Put this in your Welcome controller.

def index
  if authenticate_user?
    redirect_to :controller=>'dashboard', :action => 'index'
  else
    redirect_to '/public/example_html_file.html'
  end
end
icantbecool
  • 482
  • 8
  • 16