← Back to Upcase

Clearance - multiple roots

(Matthew Sumner) #1

In the clearance docs is the following:

Blog::Application.routes.draw do
  constraints Clearance::Constraints::SignedIn.new { |user| user.admin? } do
    root to: 'admin'

  constraints Clearance::Constraints::SignedIn.new do
    root to: 'dashboard'

  constraints Clearance::Constraints::SignedOut.new do
    root to: 'marketing'

However, in a rails 4.0.0 app I get the following error:

Invalid route name, already in use: 'root' 
You may have defined two routes with the same name using the `:as` option, or you may be overriding a route already defined by a resource with the same naming. For the latter, you can restrict the routes created with `resources` as explained here: 
http://guides.rubyonrails.org/routing.html#restricting-the-routes-created (ArgumentError)

Is there a rails 4 way to setting the root path based on the SignedIn and admin? status? I’ve previously seen this logic appear in controllers but having it in the router seems far more elegant.

I’ve seen suggestions using:

get '/', to: "where#ever", constraints: Whatever, as: nil

but I think this means you can’t use root_path anymore.

(Dolph Mullen) #2

Hey Matt,

Give this a shot:


(David Barkley) #3

You can still use root_path with as: nil as long as it’s declared on at least one of your roots. The path helper just returns the path ‘/’, it has no knowledge of the controller or action that it’s declared on really, the router handles that and it does so in a top down fashion. So whichever ‘/’ first applies to the current state of the user will be served up. You will see in rake routes that there isn’t a helper defined on your constraints but everything should work as imagined.

redirects are another option…

constraints Clearance::Constraints::SignedIn.new { |user| user.admin? } do
  get '/', to: redirect('/admin')