Rails routes based on current user

时间:2015-07-28 16:20:44

标签: ruby-on-rails ruby authentication routes rails-routing

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
end

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!

2 个答案:

答案 0 :(得分:1)

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

routes.rb

root :to => "users#new"

users_controller.rb

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

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.

答案 1 :(得分:0)

在任何家庭控制器中写下它。

def set_roots   
  if current_user      
    redirect_to dashboard_home_index_path
  else      
    redirect_to home_index_path  
  end    
end

在routes.rb文件中

root :to => 'home#set_roots'

match "/find_roots" => "home#set_roots"