With routing in Rails 3, using a namespaced route as in the following example...
namespace :admin do
get 'dashboard' => 'dashboard#index'
end
...how can I get '/admin' to route to 'dashboard#index' as well as '/admin/dashboard'? Would the best way to do it be to define...
get 'admin' => 'admin/dashboard#index'
outside the namespace or is there a more elegant way to alias a resource?
You can make the path just / which gets stripped internally by the Rails router, and just becomes /admin. The only difference is it being within your namespace instead of outside of it.
namespace :admin do
get 'dashboard' => 'dashboard#index'
get '/' => 'dashboard#index'
end
Which produces:
admin_dashboard GET /admin/dashboard(.:format) {:action=>"index", :controller=>"admin/dashboard"}
admin GET /admin(.:format) {:controller=>"admin/dashboard", :action=>"index"}
You can also do a redirect with the built in redirect method:
namespace :admin do
get 'dashboard' => 'dashboard#index'
get '/' => redirect('/admin/dashboard')
end
Or if you want to do it outside of the namespace:
get '/admin' => redirect('/admin/dashboard')
I personally like the first example best. Keeps it within the namespace and looks very similar to the default root route so it's easy to read over while working within the Admin namespaced routes.
In Rails 4 I use:
namespace :admin do
root 'dashboard#index'
end
And you can also define your custom route for /admin/dashbaord:
namespace :admin do
root 'dashboard#index'
get 'dashboard' => 'dashboard#index'
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With