Rails routes based on current user

大憨熊 提交于 2019-12-11 04:17:45

问题


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!


回答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.




回答2:


write it in any home controler.

def set_roots   
  if current_user      
    redirect_to dashboard_home_index_path
  else      
    redirect_to home_index_path  
  end    
end

in routes.rb file

root :to => 'home#set_roots'

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


来源:https://stackoverflow.com/questions/31681957/rails-routes-based-on-current-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!