简体   繁体   中英

How to set a home page for logged in users and non logged in users?

How would I set in my rails app so that if a first time user comes to my site www.example.com they see a page that they can sign in but if an already logged in goes to www.example.com it now displays their own posts but still at the same www.example.com url.

Would I do something like render template based if they are logged in or is there some other way to do this?

You can set the users#home to be the root URL:

UsersController:

def home
  if logged_in?
   @blogs = current_user.blogs
   render :action => 'logged_in'
  else
   render :action => 'non_logged_in'
  end   
end

Have 2 files in the app/views/users folder: logged_in.html.erb & non_logged_in.html.erb

A great article was writen by Steve Richert. He is using advanced constraint when defining the route, see here

It depends on how you are making your log in logic

Usually you should have two actions, one for home/login form and another for user logged in home. You can make a before_filter on your application controller, so you can test if the user is logged in or not and then redirect him to home (logged out) if not.

If you are not using your own code or another solution I would like to recommend you this gem called devise , it implements a lot of login logic itself and is easy to change too.

EDIT: I think this solutions is better than the others that were presented and I didn't put the code (although it is quite the same code of the before_filter link), so here it is:

class ApplicationController < ActionController::Base
  before_filter :require_login

  private

  def require_login
    unless logged_in?
      flash[:error] = "You must be logged in to access this section"
      render :controller => 'home', :action => 'not_logged_in'
    else
      # whatever code you need to load from user
      render :controller => 'home', :action => 'logged_in'
    end
  end

end

This solutions works perfectly because it tests if the user is logged in in every controller/action he tries to access.

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