Cyriac Domini Thundathil Cyriac Domini Thundathil - 6 months ago 24x
Ruby Question

Rails routes based on current user

I followed this rails cast to create authentication for a rails project. My routes currently look like this:

Rails.application.routes.draw do
resources :messages

get "log_out" => "sessions#destroy", :as => "log_out"
get "log_in" => "sessions#new", :as => "log_in"
get "sign_up" => "users#new", :as => "sign_up"
get "new_photo" => "users#edit", :as => "new_photo"
root :to => "users#new"
resources :users
resources :sessions

How to I edit this file so that the root will be pointing to "messages#new", if a user is logged in and "users#new" when no user is logged in? I tried many of the solutions on other pages, but they didnt work (they were probably for devise). Thanks for the help!


You'll probably want to handle this in your controller.


root :to => "users#new"


def new
  return redirect_to new_messages_url if current_user
  # normal controller code below...

This will redirect the logged_in user (current_user) to the new messages page if already logged in. I'm just assuming that current_user holds your user data, it may be different for your application.