I have admins and normal users in my webapp. I want to make their root (/) different depending on who they are. The root is accessed from many different pages, so it would be much easier if I could make this happen in the routes.rb file. Here is my current file.
ProjectManager::Application.routes.draw do
root :to => "projects#index"
end
Can someone please link me to an example that can show me the direction to go in? Is there any way to put logic into the routes file? Thanks for all the help.
You can just create controller for root route.
In your routes.rb:
P.S. example expects using Devise, but you can customize it for your needs.
There are a few different options:
1. lambda in the routes file(not very railsy)
previously explained
2. redirection in application controller based on a before filter(this is optimal but your admin route will not be at the root)
source rails guides - routing
you would have two routes, and two controllers. for example you might have a
HomeController
and then anAdminController
. Each of those would have anindex
action.your
config/routes.rb
file would haveThe namespace method gives you a route at
/admin
and the regular root would be accessible at'/'
Then to be safe; in your admin controller add a before_filter to redirect any non admins, and in your home controller you could redirect any admin users.
3. dynamically changing the layout based on user role.
In the same controller that your root is going to, add a helper method that changes the layout.
Then in your layouts folder, add a file called
admin.html.erb
source: rails guides - layouts and routing
You can't truly change the root dynamically, but there's a couple of ways you can fake it.
The solution you want needs to take place in either your application controller or the "default" root controller. The cleanest/easiest solution is simply to have your application controller redirect to the appropriate action in a before filter that only runs for that page. This will cause the users' url to change, however, and they won't really be at the root anymore.
Your second option is to have the method you've specified as root render a different view under whatever conditions you're looking for. If this requires any major changes in logic beyond simply loading a separate view, however, you're better off redirecting.