Search code examples
ruby-on-railsroutescatch-all

Match id at base path rather than under controller name


Say I have a User Model. And a route such as this:

http://www.mycoolapp.com/users/1

How can I match http://www.mycoolapp.com/1 where 1 matches the first User, without using /users/1.

Do you use a catch all? How is this accomplished in rails routing?


Solution

  • Your Routes file will need to look something like this, assuming you already have a User resource:

    YourApp::Application.routes.draw do
      ....
      ....
      resources :user
    
      get ":id" => "users#show", :as => 'root_user'
    end
    

    The very last line - and it must be last, so it doesn't override other urls in your application - manually creates a path that should work. You can also reference it using 'root_user_path' in your code to create the links.