Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with multiple root paths and scopes in Rails

We have the following routes setup:

MyApp::Application.routes.draw do
  scope "/:locale" do    
    ...other routes
    root :to => 'home#index'
  end
  root :to => 'application#detect_language'
end

Which gives us this:

root      /:locale(.:format)    home#index
root      /                     application#detect_language

which is fine.

However, when we want to generate a route with the locale we hitting trouble:

root_path generates / which is correct.

root_path(:locale => :en) generates /?locale=en which is undesirable - we want /en

So, question is, is this possible and how so?

like image 919
Neil Middleton Avatar asked Aug 09 '12 11:08

Neil Middleton


People also ask

What is the difference between resources and resource in Rails?

Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.

How do I see all routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.


1 Answers

root method is used by default to define the top level / route. So, you are defining the same route twice, causing the second definition to override the first!

Here is the definition of root method:

def root(options = {})
  options = { :to => options } if options.is_a?(String)
  match '/', { :as => :root, :via => :get }.merge(options)
end

It is clear that it uses :root as the named route. If you want to use the root method just override the needed params. E.g.

scope "/:locale" do    
  ...other routes
  root :to => 'home#index', :as => :root_with_locale
end
root :to => 'application#detect_language'

and call this as:

root_with_locale_path(:locale => :en)

So, this is not a bug!

like image 121
Neil Middleton Avatar answered Sep 17 '22 22:09

Neil Middleton