Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect root to named route in rails 4

I'm trying to redirect my www.example-app.com root to www.example-app.com/app/dashboard using routes.rb. At the moment i'm doing it like so:

root to: redirect('/app/dashboard')

But would like to do that using named route, for example:

get 'app/dashboard' => 'accounts#dashboard', as: :account_dashboard

But when i put that in routes:

root to: redirect(account_dashboard_url)

... of course it doesn't work, how can i do it?

like image 754
plunntic iam Avatar asked Feb 28 '15 16:02

plunntic iam


People also ask

How do I redirect in Rails?

Rails's redirect_to takes two parameters, option and response_status (optional). It redirects the browser to the target specified in options. This parameter can be: Hash - The URL will be generated by calling url_for with the options.

What is match in Rails routes?

Rails routes are matched in the order they are specified, so if you have a resources :photos above a get 'photos/poll' the show action's route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.


2 Answers

You can't do this directly in routes.rb (as of now – Rails 4.2), but there are ways to make it work. The simplest, IMO, would be to create a method in your application controller to do the redirection.

# routes.rb

root to: 'application#redirect_to_account_dashboard'

and

# application_controller.rb

def redirect_to_account_dashboard
  redirect_to account_dashboard_url
end
like image 132
dbenton Avatar answered Sep 28 '22 08:09

dbenton


Please note, that as of Rails 5, redirecting from the routes is possible.

match "*", to: redirect('/something-else'), via: :all

http://guides.rubyonrails.org/routing.html#redirection

This page is quite high on some Google-keywords, and this might be misleading.

like image 41
Frederik Spang Avatar answered Sep 28 '22 08:09

Frederik Spang